繁体   English   中英

字符串索引两个字符串之间的差异

[英]String index of Difference between two Strings

我有两个字符串列表,如下所示:

List1(由sql结果集生成)

10001
10100
10001

List2(由sql结果集生成)

10000
10000
10000

按钮动作;

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        try {
            // TODO add your handling code here:
            createList1();
            createList2();
            difference();
        } catch (Exception ex) {
            Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
        }       
    }    

差异无效;

public void difference (){
       int minLen = Math.min(List1.get(0).length(), List2.get(0).length());
        for (int i = -1 ; i != minLen ; i++) {
          char chA = List1.get(0).charAt(i);
          char chB = List2.get(0).charAt(i);
        if (chA != chB) {
        System.out.println(chA);
        }
       }  
    }

我想找到List1中索引0的哪些索引号不同。

提前致谢。

创建一个循环,将索引i从两个字符串中较短字符串的长度为零,并使用==运算符逐个比较字符:

int minLen = Math.min(a.length(), b.length());
for (int i = 0 ; i != minLen ; i++) {
    char chA = a.charAt(i);
    char chB = b.charAt(i);
    if (chA != chB) {
        ...
    }
}

在开始比较之前,您需要检查ab是否为null 否则,获取长度将触发空引用异常。

试试这个:

public List<Integer> findDiffIndexes(String s1, String s2 ) {
    List<Integer> indexes = new ArrayList<Integer>();
    for( int i = 0; i < s1.length() && i < s2.length(); i++ ) {
        if( s1.charAt(i) != s2.charAt(i) ) {
            indexes.add( i );
        }
    }
    return indexes;
}

在List 1和List2上循环,并比较索引值,我假设你们两个列表都有相同的大小,

for(int i=0;i<list1.size();i++)
{
  if(!list1.get(i).equals(list2.get(i))
   {
     System.out.println("Not equal value of Index="+i);
   }
}

假设这两个字符串的长度总是相同的......

String first = "10000";
String second = "10101";

ArrayList differentIndexes = new ArrayList();

for(int i=0; i<first.length(); i++){
if(first.charAt(i)!=second.charAt(i)){
differentIndexes.add(i);
}
}

https://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/StringUtils.html#difference%28java.lang.String,%20java.lang.String%29

public static String difference(String str1,String str2)

比较两个字符串,并返回它们不同的部分。 (更准确地说,返回第二个String的其余部分,从它与第一个字符串的不同开始。)

例如,差异(“我是机器”,“我是机器人”) - >“机器人”。

  StringUtils.difference(null, null) = null StringUtils.difference("", "") = "" StringUtils.difference("", "abc") = "abc" StringUtils.difference("abc", "") = "" StringUtils.difference("abc", "abc") = "" StringUtils.difference("ab", "abxyz") = "xyz" StringUtils.difference("abcde", "abxyz") = "xyz" StringUtils.difference("abcde", "xyz") = "xyz" Parameters: str1 - the first String, may be null str2 - the second String, may be null Returns: the portion of str2 where it differs from str1; returns the empty String if they are equal Since: 2.0 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM