Reputation: 16255
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'")
Upvotes: 5
Views: 12852
Reputation: 62759
The other peoples answers are better, but under the assumption you are trying to learn, I wanted to point out the problems with your original code.
Here would be a "Fixed" version of what you are trying to do (Using your style, which was close) and the things you need to do to make it work:
public String quoteLetters(String s)
{
return s.replace("A", "'A'").replace("B", "'B'").replace("C", "'C'");
}
Here are the problems you had:
Upvotes: 1
Reputation: 1108642
I think regex is not really suitable if those are fairly complex strings.
Consider just wrapping it in your own utility method taking arrays or lists as arguments.
public static String replace(String string, String[] toFind, String[] toReplace) {
if (toFind.length != toReplace.length) {
throw new IllegalArgumentException("Arrays must be of the same length.");
}
for (int i = 0; i < toFind.length; i++) {
string = string.replace(toFind[i], toReplace[i]);
}
return string;
}
Maybe there's already one in the Apache Commons or Google Code. Give it a look if you prefer 3rd party API's above homegrown stuff.
Edit: why downvoting a technically correct but a in your opinion not preferred answer? Just don't upvote.
Upvotes: 2
Reputation: 838066
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.
Upvotes: 16
Reputation: 570315
Have a look at StringUtils
from Apache Commons Lang and its various replace
methods.
Upvotes: 3
Reputation: 625037
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'
Upvotes: 10