Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String replace in Java

Tags:

java

string

regex

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'")
like image 901
Aly Avatar asked Dec 23 '09 00:12

Aly


People also ask

What is string replace in Java?

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.

What is the difference between Replace () and replaceAll ()?

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)

Can you replace characters in a string Java?

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.

How do I replace text in a string?

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.


3 Answers

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.

like image 139
Mark Byers Avatar answered Oct 11 '22 12:10

Mark Byers


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'
like image 35
cletus Avatar answered Oct 11 '22 13:10

cletus


Have a look at StringUtils from Apache Commons Lang and its various replace methods.

like image 32
Pascal Thivent Avatar answered Oct 11 '22 14:10

Pascal Thivent