I currently have a string which contains the characters A, B and C for example the string looks like
"A some other random stuff B C"
the other random stuff doesn't contain A, B or C I want to replace the A, B & C with 'A', 'B' and 'C' respectively what's the best way to do that currently I'm doing:
String.replace("A", "'A'").replace("B", "'B'").replace("C", "'C'")
Java String replace() Method The replace() method searches a string for a specified character, and returns a new string where the specified character(s) are replaced.
The only difference between them is that it replaces the sub-string with the given string for all the occurrences present in the string. Syntax: The syntax of the replaceAll() method is as follows: public String replaceAll(String str, String replacement)
The Java String class replace() method returns a string replacing all the old char or CharSequence to new char or CharSequence. Since JDK 1.5, a new replace() method is introduced that allows us to replace a sequence of char values.
The replace() method searches a string for a value or a regular expression. The replace() method returns a new string with the value(s) replaced. The replace() method does not change the original string.
cletus' answer works fine if A, B and C are those exact single characters, but not if they could be longer strings and you just called them A, B and C for example purposes. If they are longer strings you need to do:
String input = "FOO some other random stuff BAR BAZ";
String output = input.replaceAll("FOO|BAR|BAZ", "'$0'");
You will also need to escape any special characters in FOO, BAR and BAZ so that they are not interpreted as special regular expression symbols.
Use a regular expression:
String input = "A some other random stuff B C";
String output = input.replaceAll("[ABC]", "'$0'");
Output:
'A' some other random stuff 'B' 'C'
Have a look at StringUtils
from Apache Commons Lang and its various replace
methods.
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