Java String replace With Examples

Java String replace methods are used to replace part of the string with some other string. These string replace methods are sometimes very useful; for example replacing all occurrence of “colour” to “color” in a file.

Java String replace

Java String class has four methods to replace a substring. Two of these methods accept regular expressions to match and replace part of the string.

  1. public String replace(CharSequence target, CharSequence replacement): This method replaces each substring of this string with the replacement string and return it. Note that replacement happens from start of the string towards end of the string. This behaviour can be easily confirmed by below code snippet.
  2. public String replace(char oldChar, char newChar): This method is used to replace all occurrences of oldChar character to newChar character.
  3. public String replaceAll(String regex, String replacement): This is a very useful method because we can pass regex to match and replace with the replacement string.
  4. public String replaceFirst(String regex, String replacement): This string replacement method is similar to replaceAll except that it replaces only the first occurrence of the matched regex with the replacement string.

Let’s look into java string replace methods with example code.

Java String replace character example

One of the popular use case for character replacement is to change a delimiter in a string. For example, below code snippet shows how to change pipe delimiter to comma in the given string.

Java String replace() example

Let’s look at java string replace method example to replace target string with another string. I will take user input from java scanner class for source, target and replacement strings.

Below image illustrates the output of one of the execution of above program.

java-string-replace-char

Java String replaceAll example

If you notice above program output, target string should be an exact match for replacement. Sometimes it’s not possible because the input string may be different because of case. In this scenario we can use replaceAll method and pass regular expression for case insensitive replacement. Let’s look at a simple program where we will match and replace string with case insensitivity.

Did you notice the prefix (?i) to the search term? This is to pass regex to match strings with case insensitive way. Below image shows the output where both “Android” and “android” terms are getting replaced with “Java” because we used replaceAll method.

java-string-replaceAll-example

Java String replaceFirst example

Java String replaceFirst is used to replace only the first matched regex string with the replacement string. Let’s look at a simple example of String replaceFirst method.

That’s all for java String replace methods with example code.

Reference: String API Doc

By admin

Leave a Reply