且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用多个不同的字符替换String中的多个字符

更新时间:2023-02-12 19:23:20

你不需要使用正则表达式,你可以使用两个替换来解决你的问题:

You dont need to use regex, you can use two replace to solve your problem :

String replace = convert.replace("1", "one ").replace("0", "zero ");






示例:


Example :

int i = 55;
System.out.println(Integer.toBinaryString(i));
System.out.println(Integer.toBinaryString(i).replace("1", "one ").replace("0", "zero "));

输出

110111
one one zero one one one 






超过一年后编辑。


Edit after more than one year.

作为 @ Soheil Pourbafrani 在评论中询问,是否可以只遍历字符串一次,是的,你可以,但你需要使用这样的循环:

As @Soheil Pourbafrani ask in comment, is that possible to traverse the string only one time, yes you can, but you need to use a loop like so :

int i = 55;
char[] zerosOnes = Integer.toBinaryString(i).toCharArray();
String result = "";
for (char c : zerosOnes) {
    if (c == '1') {
        result += "one ";
    } else {
        result += "zero ";
    }
}
System.out.println(result);
=>one one two one one one



Java 8 +



如果您使用的是Java 8+,则更容易使用:

Java 8+

Or more easier if you are using Java 8+ you can use :

int i = 55;
String result = Integer.toBinaryString(i).chars()
        .mapToObj(c -> (char) c == '1' ? "one" : "two")
        .collect(Collectors.joining(" "));
=>one one two one one one