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.

  1. String replace(char oldChar, char newChar)
  2. String replace(CharSequence target,CharSequence replacement)
  3. String replaceFirst(String regex, String replacement)
  4. 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
	}
}
Output: Replace char w with b : 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
	}
}
Output: Replace char sequence aaa with bb : bba

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"));  
	}
}
Output: Replace string comes aftre bo : This is a 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"));  
	}
}
Output: Replace substring ‘book cover’ with ‘house’ : This is a house and this house looks beautiful.
Ask Question
Have any question or suggestion for us?Please feel free to post in Q&A Forum
Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...