JAVA replace string


Replaces each substring of this string that matches the given regular expression with the given replacement.

String s = “This is a string”;
s = s.replaceAll(” “,””);

s now equals “Thisisastring”

All white spaces have been replaced with the empty string.

JAVA replace string within a string

The following code replaces an instance of a string within a string:

String testString = “This is a text string”
testString = testString.replace(“text string”, “sentance”);

testString will now print “This is a sentance”.

The replace() function is case sensative, and will only carry out the replace if the case matches both strings.