Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/370.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 用多个不同的字符替换字符串中的多个字符_Java_Regex_String_Replace_Binary - Fatal编程技术网

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

Java 用多个不同的字符替换字符串中的多个字符,java,regex,string,replace,binary,Java,Regex,String,Replace,Binary,我正在编写一个代码,将二进制数字转换为相应的字值 例如,我输入“3”,代码将把数字转换为“11”,这是“3”的二进制表示形式。代码将继续将“11”转换为将被输出的“1” 我已经写了二进制转换部分,但是我很难把它转换成单词 public class BinaryWords { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = ne

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

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

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

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);
        }
    }
}
公共类二进制字{
公共静态void main(字符串[]args){
//TODO自动生成的方法存根
扫描仪sc=新的扫描仪(System.in);
字符串S=sc.nextLine();//for循环将重复多少次
对于(int i=0;i
我尝试将replaceAll函数与regex[1,0]一起使用,我认为它会将1和0转换为下一个字段中指定的序列

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


感谢您的帮助,谢谢

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

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 

超过一年后编辑

如注释中所述,是否可以只遍历字符串一次,是的,您可以,但您需要使用如下循环:

Java 8之前 爪哇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
方法都将遍历
字符串
,而我们可以在一次遍历中进行替换。我不知道java是否会优化这样一个只需一次遍历即可完成的行内替换方法?@SoheilPourbafrani是的,你可以,检查我的编辑我发布了另外两个解决方案希望这能帮助你:)相关-
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