繁体   English   中英

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

[英]Replacing a character in a string from another string with the same char index

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

例:

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

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

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

这是我的代码:

    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();
}

这很简单。 您创建一个新的字符串生成器。 尽管仍可以在字符串生成器中找到xXindexOf('X') != -1 ),但获取索引并设置setCharAt

文档说您使用String.replace(char, char)的方式错误

返回一个新字符串,该字符串是用newChar替换此字符串中所有出现的oldChar的结果。

因此,如果您有多个字符,它将用相同的值替换每个字符。

您只需要在特定位置“更改”字符,为此,最简单的方法是使用String.toCharArray可以获取的char数组,由此,您可以使用相同的逻辑。

当然,您可以使用String.indexOf查找特定字符的索引

注意: char c = 'x'|'X' ; 不会给您预期的结果。 这将执行二进制操作,给出的值不是您想要的值。

如果一位为1,则OR将返回1。

0111 1000 (x)
0101 1000 (X)
OR
0111 1000 (x)

但是结果将是一个整数(每个数字运算都至少返回一个整数,您可以找到有关此信息的更多信息)

您在这里有两种解决方案,可以使用两个变量(或数组),也可以使用String.toLowerCase ,仅使用char c = 'x'

暂无
暂无

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

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