返回两个字符串不同的数组位置

Mr *_*ker 2 java

我试图检查数组中两个字符串的位置是否不同.例如,如果我有字符串apple和字符串,appendix那么两个字符串在i = 3的位置是不同的.

如何用Java检查?

 //The first string is s.
    char[] cArray = s.toCharArray();
    // The seond string is root.edge.
    char[] rootEdgeCharacter = root.edge.toCharArray();

    for(int i=0; i<cArray.length; i++  ){
        for(int j=0; j<rootEdgeCharacter.length; j++){
            if(cArray[i]== rootEdgeCharacter[j]){
                System.out.println("The String are different where i =" + i);

            }
        }
    }   
Run Code Online (Sandbox Code Playgroud)

fge*_*fge 5

不要使用.toCharArray(),它会不必要地创建一个新的字符数组.请改用.charAt().

更重要的是,你的代码不会"并行"地遍历数组:你在索引0,0,然后是1,0,然后是3等等迭代.这不是你想要的.

这是一个解决方案; 请注意,对于不等长的字符串,它将返回较小的长度,并且两个字符串相等,它返回-1:

public static int findDifferingIndex(final String s1, final String s2)
{
    final int len1 = s1.length();
    final int len2 = s2.length();
    final int len = Math.min(len1, len2);

    for (int index = 0; index < len; index++)
        if (s1.charAt(index) != s2.charAt(index))
            return index;

    // Check the length of both strings; if they are equal, return -1.
    // Otherwise return the length `len`.
    return len1 == len2 ? -1 : len;
}
Run Code Online (Sandbox Code Playgroud)