gpt4 book ai didi

java - 用具有相同字符索引的另一个字符串替换字符串中的字符

转载 作者:行者123 更新时间:2023-12-01 08:54:49 27 4
gpt4 key购买 nike

我正在尝试搜索并显示字符串中的未知字符。两个字符串的长度都是 12。

示例:

     String s1 = "1x11222xx333";
String s2 = "111122223333"

程序应该检查 s1 中由 x|X 表示的所有未知数,并获取 s2 中的相关字符,并用相关字符替换 x|X。

到目前为止,我的代码仅用 s2 中的相关字符替换了第一个 x|X,但使用第一个 x|X 的字符打印了其余未知数的重复项。

这是我的代码:

    String VoucherNumber = "1111x22xx333";
String VoucherRecord = "111122223333";
String testVoucher = null;
char x = 'x'|'X';

System.out.println(VoucherNumber); // including unknowns


//find x|X in the string VoucherNumber
for(int i = 0; i < VoucherNumber.length(); i++){

if (VoucherNumber.charAt(i) == x){

testVoucher = VoucherNumber.replace(VoucherNumber.charAt(i), VoucherRecord.charAt(i));

}


}

System.out.println(testVoucher); //after replacing unknowns
}


}

最佳答案

我一直很喜欢使用 StringBuilder,所以这里有一个使用它的解决方案:

private static String replaceUnknownChars(String strWithUnknownChars, String fullStr) {
StringBuilder sb = new StringBuilder(strWithUnknownChars);
while ((int index = Math.max(sb.toString().indexOf('x'), sb.toString().indexOf('X'))) != -1) {
sb.setCharAt(index, fullStr.charAt(index));
}

return sb.toString();
}

这非常简单。您创建一个新的字符串生成器。虽然仍然可以在字符串生成器中找到 xX (indexOf('X') != -1),但获取索引和setCharAt

关于java - 用具有相同字符索引的另一个字符串替换字符串中的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42106147/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com