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
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'
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With