将字符串中的多个字符替换为多个不同的字符

Gla*_*ace 4 java regex string binary replace

我正在研究一种将二进制数字转换为其相应的单词值的代码。

例如,我输入“3”,代码会将数字转换为“11”,这是“3”的二进制表示形式。该代码将继续将“11”转换为“一一”并输出。

我已经写了二进制转换部分,但我很难将其转换为单词。

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我尝试将 ReplaceAll 函数与正则表达式 [1, 0] 一起使用,(我认为)它将(两者?) 1 和 0 转换为下一个字段中指定的序列。

我想将每个 1 转换为“一”,将每个 0 转换为“零”。

任何帮助表示赞赏,谢谢!

YCF*_*F_L 5

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

String replace = convert.replace("1", "one ").replace("0", "zero ");
Run Code Online (Sandbox Code Playgroud)

例子 :

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

输出

110111
one one zero one one one 
Run Code Online (Sandbox Code Playgroud)

时隔一年多再编辑。

正如@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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)