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

4

我正在编写一段代码,将二进制数字转换为对应的单词值。

例如,我输入“3”,代码将把数字转换为“11”,这是“3”的二进制表示。代码将继续将“11”转换为“one one”,并输出结果。

我已经编写了二进制转换部分,但是我在将其转换为单词时遇到了困难。

public class BinaryWords {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        String S = sc.nextLine(); //how many times the for loop will repeat
        for (int i = 0; i < S.length() + 1; i++) {
            int A = sc.nextInt(); //input the number
            String convert = Integer.toBinaryString(A); //converts the number to binary String
            String replace = convert.replaceAll("[1 0]", "one, zero "); //replaces the String to its value in words
            System.out.println(replace);
        }
    }
}

我尝试使用replaceAll函数和正则表达式[1,0],它将把1和0都转换为下一个字段中指定的序列(我认为)。
我想把每个1都转换为“one”,每个0都转换为“zero”。
感谢您的帮助!

如何用单个字符替换多个可能的字符?相关链接 - https://dev59.com/Omox5IYBdhLWcg3wTina - MasterJoe
1个回答

4
您不需要使用正则表达式,可以使用两个替换函数来解决您的问题:
String replace = convert.replace("1", "one ").replace("0", "zero ");

例子:

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 

一年多后的编辑。

正如@Soheil Pourbafrani在评论中提到的那样,是否可以只遍历字符串一次,是的,你可以,但需要使用循环,例如:

Java 8之前

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或更高版本,则可以更加轻松地使用以下内容:

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

1
谢谢!我不知道你可以在一行中使用多个替换。 - Glace
是的,@Glace,你可以这样做,因为替换返回字符串。 - Youcef LAIDANI
使用两个replace函数连续调用是否最优?因为每个“replace”方法都会遍历字符串,而我们可以在一次遍历中完成替换。我不知道Java是否会优化这样的连续替换方法以在一次遍历中完成。 - Soheil Pourbafrani
@SoheilPourbafrani 是的,你可以这样做,检查我的编辑,我发布了另外两个解决方案,希望这能帮到你 :) - Youcef LAIDANI

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接