Java String Handling RegEx

Java String replace Example

Java String replace Example shows how to replace string with other string in Java. Example also shows how to replace a character, first occurrence or all occurrences of string in Java.

How to replace a character in String in Java?

To replace a character in String, you can use replace method of Java String class.

This method replaces all occurrences of the specified character with new character and returns the result in a new String.

Java String replace character example

Output

Note: If the specified character does not exists in the String, then the reference to the original String is returned. Otherwise a new String object is created as a result of replacement and returned.

Please also note that, since String is immutable (cannot be changed once created), replace method does not change the original String but returns a new String as given below.

Output

Make sure to assign the result of replace method back to the original String if you want the result in the original string.

How to replace string with another string?

To replace string with another string, you can use replace method of String class.

This method replaces all the occurrences of specified string with the replacement string and returns result in a new String.

Java String replace example

Output

If the string does not contain the specified string, reference of the original string is returned. Otherwise, a new string is created as a result of replacement and returned.

Important note: Even though the name of the method is replace, it replaces ALL the occurrences of specified string in a given string not just one as given below.

Output

How to replace first occurrence of string with other string in Java?

To replace only first occurrence of a String within String, use replaceFirst method.

This method replaces first substring that matches the regular expression with the replacement. It returns the result in a new string.

Output

Important Note: replaceFirst method accepts regular expression while replace method does not. For example, below given code replaces first digit of the String with the empty String using regular expression.

Output

If you want to specify regular expression, you should use replaceAll method instead.

How to replace a string with Apache Commons library?

If you are using Apache Commons library, you can use replace method of StringUtils class as given below.

Output

Please let us know your views in the comments section below.

 

Join 1000+ fellow learners! Enter your email address below: