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

时间:2022-12-30
本文介绍了用多个不同的字符替换 String 中的多个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

I am working on a code that will convert binary digits to its corresponding value in words.

例如,我输入3",代码会将数字转换为11",即3"的二进制表示.代码将继续将11"转换为one one",然后输出.

For example, I would input "3" and the code will convert the number to "11", which is the binary representation of "3". The code will proceed to convert that "11" to "one one" which will be outputted.

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

I have already wrote the binary conversion part, but I am having difficulty converting it to words.

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 转换为下一个字段中指定的序列.

I tried using the replaceAll function with the regex [1, 0], which (I think) will convert (both?) 1 and 0 to the sequence specified in the next field.

我想将每个 1 转换为一",将每个 0 转换为零".

I would like to convert every 1 to a "one" and every 0 to a "zero".

感谢任何帮助,谢谢!

推荐答案

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

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

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 

<小时>

一年多后修改.


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

这篇关于用多个不同的字符替换 String 中的多个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:java:将二进制字符串转换为int 下一篇:Java二进制补码到整数

相关文章

最新文章