String methods – replace
In this post, we will discuss about replace(),replaceFirst() and replaceAll. As it name says , method replace is used to replace a sequence of characters in a string with a expected characters or substring.
There are 4 types of implementations of replace.
- String replace(char oldChar, char newChar)
- String replace(CharSequence target,CharSequence replacement)
- String replaceFirst(String regex, String replacement)
- String replaceAll(String regex, String replacement)
Let’s understand them with examples.
String replace(char oldChar, char newChar):
This will replace the old character with a new character.
e.g. Take string “Wall” and replace char ‘w’ with char ‘b’. Look at the below example for result.
public class ExampCompareTo { public static void main(String[] args) { String val1 = "wall"; System.out.println("Replace char w with b : "+val1.replace("w", "b")); // result will ball } }
String replace(CharSequence target,CharSequence replacement):
This method will returns string after replacing a sequence of characters with the a new sequence of characters.
e.g. If we replace “aaa” with “bb” in the string “aaaa” , it will result “bba”.
public class ExampCompareTo { public static void main(String[] args) { String val1 = "aaaa"; System.out.println("Replace char sequence aaa with bb : "+val1.replace("aaa", "bb")); // result will ball } }
String replaceFirst(String regex, String replacement):
It replaces the first substring of this string that matches the given regular expression with the expected substring.
e.g. In the example below, it will replace the whole string which comes after substring “bo”, with substring “house”.
public class ExampCompareTo { public static void main(String[] args) { String val1 = "This is a book cover."; System.out.println("Replace string comes aftre bo : "+val1.replaceAll("bo(.*)", "house")); } }
String replaceAll(String regex, String replacement):
It replaces the all substrings of this string that matches the given regular expression with the expected substring.
public class ExampCompareTo { public static void main(String[] args) { String val1 = "This is a book cover and this book cover looks beautiful."; System.out.println("Replace substring 'book cover' with 'house' : "+val1.replaceAll("book cover", "house")); } }