String replace methods example

String replace methods are used to replace a part of string with a new string.
We have 4 variations for replace in String

String replace(char oldChar, char newChar) returns a new String with the oldChar replaced with a newChar that was specified.

String replace(CharSequence target, CharSequence replacement) returns a new String by replacing a sequence of characters that are specified.

String replaceAll(String regex, String replacement) returns a new String by replacing all the matching regular expression with a new replacement String.

String replaceFirst(String regex, String replacement) returns a new String by replacing only the first matching regular expression with a new replacement String.

String replace methods example

1. replace() example

Output

2. replaceAll() example

Output

3. replaceFirst() example

Output

Reference

1. String API

It's only fair to share...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn