恢复 2 个字符串之间的错误字符

我有 2 个字符串:str1 和 str2 它们几乎相同。

str1 = 001

str2 = 101

正如你在上面看到的,如果我比较 str1 和 str2,'1' 是错误的字符。我想用另一个替换这个字符:'X'

str1 = 001

str2 = X01

这是我的方法,它返回一个字符串并有 2 个字符串参数(str1 和 str2):

    char charArray1[] = str1.toCharArray();

    char charArray2[] = str2.toCharArray();

    String str = "";

    

    for(int i=0; i<charArray1.length; i++){

        if(charArray1[i] != charArray2[i]){

            charArray2[i]='X';

        }       

    str = new String(charArray2);

    }

    System.out.print(str1 + " is now : " + str + "\n");

    return str;

但我不知道为什么它不起作用。确实,我不能修改 str2 的错误字符“1”(我想要 X01 而不是 101)。你知道为什么吗?


白板的微信
浏览 104回答 2
2回答

茅侃侃

&nbsp; &nbsp; String str1 = "001";&nbsp; &nbsp; String str2 = "101";&nbsp; &nbsp; char charArray1[] = str1.toCharArray();&nbsp; &nbsp; char charArray2[] = str2.toCharArray();&nbsp; &nbsp; String str = "";&nbsp; &nbsp; for(int i=0; i<charArray1.length; i++){&nbsp; &nbsp; &nbsp; &nbsp; if(charArray1[i] != charArray2[i])&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; charArray2[i] = 'X';&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp;else&nbsp; &nbsp; str = new String(charArray2);&nbsp; &nbsp; }&nbsp; &nbsp; System.out.print(str1 + " is now : " + str + "\n");

UYOU

str全部完成后应该分配一次。无需为两个字符串创建一个 char 数组...char charArray1[] = str1.toCharArray();for(int i=0; i<charArray1.length; i++) {&nbsp; &nbsp; if (charArray1[i] != str2.get(i)) {&nbsp; &nbsp; &nbsp; &nbsp; charArray1[i] = 'X';&nbsp; &nbsp; }}String str = new String(charArray1);System.out.println(str1 + " is now : " + str);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java