Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the new value of new replaced string? [duplicate]

Tags:

java

string

Im still new at java. Is there a way to get the new string that have been replaced ?

import java.io.*;
public class Test {

    public static void main(String args[]) {
        String str = new String("wew");
        System.out.println(str.replaceAll("w", "61"));
        System.out.println(str.replaceAll("e", "31"));
    }
}

output:

61e61
w31w

Desired new output:

613161

I want to get the output string 61e61 then replaced the e to 31

like image 859
Ror Schach Avatar asked Dec 05 '22 10:12

Ror Schach


2 Answers

You can chain replaceAll as:

System.out.println(str.replaceAll("w", "61").replaceAll("e", "31"));

Currently, you're returning two different strings with both your print statements.

System.out.println(str.replaceAll("w", "61")); // returns new string '61e61'
System.out.println(str.replaceAll("e", "31")); // returns new string 'w31w'
like image 169
Naman Avatar answered Dec 08 '22 00:12

Naman


You're using it wrong. The method replaceAll of the Class String returns a String.

You have to use the return value again (which can be written in one line):

    String str = "wew".replaceAll("w", "61").replaceAll("e", "31");
    System.out.println(str);

Outputs: 613161

like image 31
maio290 Avatar answered Dec 07 '22 23:12

maio290