【问题标题】:Replace multiple characters in String with multiple different characters用多个不同的字符替换 String 中的多个字符
【发布时间】:2017-09-28 21:50:13
【问题描述】:

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

例如,我输入“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 转换为“一”,将每个 0 转换为“零”。

感谢任何帮助,谢谢!

【问题讨论】:

标签: java regex string replace binary


【解决方案1】:

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

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

【讨论】:

  • 谢谢!不知道你可以在一行中使用多个替换。
  • 是的@Glace 你可以这样做,因为替换返回字符串
  • 连续使用两个替换功能是否最佳!因为每个replace 方法都会遍历String,而我们只需一次遍历即可完成替换。不知道java会不会优化这样一个在一次遍历中完成的连续替换方法?
  • @SoheilPourbafrani 是的,你可以,检查我的编辑我发布了另外两个解决方案希望这可以帮助你:)
猜你喜欢
  • 1970-01-01
  • 2020-06-02
  • 1970-01-01
  • 2022-12-15
  • 2021-10-23
  • 2017-01-06
  • 1970-01-01
  • 2020-08-31
  • 1970-01-01
相关资源
最近更新 更多