Java: String replace() method

In this article, we will discuss different variants of replace methods to replace character/substring with another new string using String’s replace() method

 

replace() method:

  • This String method is used to replace old character/substring with new character/substring

Note:

  • there are 2 variants or overloaded replace() methods
  • in addition to this, there are 2 more methods similar to replace() method viz.;
  • these methods are replaceAll() and replaceFirst()

Method Signature:

public String replace(char oldChar, char newChar);
public String replace(CharSequence target, 
		CharSequence replacement);
 
public String replaceAll(String regex, String replacement);
public String replaceFirst(String regex, String replacement);

Parameters:

  • oldChar           –> old character which need to be replaced
  • newChar         –> new character which will replaces the old character
  • target               –> target string which need to be replaced
  • regex                –> regular expression to which this string is to be matched
  • replacement   –> new string which will replaces the matching invoking string

 Returns:

replace() method

Returns

replace(char oldChar, char newChar); Returns  a string, after replacing all occurrences of old-character with new-character

Note: It’s just for single character

replace(CharSequence target, CharSequence replacement); Returns  a string, after replacing all occurrences of old-character-sequence (old string) with new-character-sequence (new string)

Note: It’s for sequence of characters i.e.; sub-string

replaceAll(String regex, String replacement); Returns  a string, after replacing all occurrences of invoking-string with replacement string that matches the specified regular expression

Throws PatternSyntaxException, if the specified regular-expression is invalid

replaceFirst(String regex, String replacement); Returns  a string, after replacing 1st occurrence of invoking-string with replacement string that matches the specified regular expression

Throws PatternSyntaxException, if the specified regular-expression is invalid

 

Difference between replace(), replaceAll() and replaceFirst() methods

  • In replace() method, all matches of old character (or substring) will be replaced with new character (or substring) –> are either char or CharSequence
  • Whereas in replaceAll() method, both replacement substring and regex for pattern matching –> are strings
  • replaceFirst() method is another variant similar to replaceAll() method which replaces only the 1st occurrence of invoking string in accordance with regex pattern matching

 

Example 1: replace() method for character

  • Java program to showcase how to replace old character with new character using String’s replace() method

StringReplaceMethod.java

package in.bench.resources.string.methods;

public class StringReplaceMethod {

	public static void main(String[] args) {

		// Example 1: test string
		String testStr1 = "penguins are rare species";

		// replace all 'p' with 'v'
		String replacedStr1 = testStr1.replace('p', 'v');

		// print to console
		System.out.println("Example 1 : replace('p', 'v') \n");
		System.out.println("The original string is : " 
				+ testStr1);
		System.out.println("The replaced string is : " 
				+ replacedStr1);


		// Example 2: test string
		String testStr2 = 
				"all human being born with special talent";

		// replace all 'a' with 'b'
		String replacedStr2 = testStr2.replace('a', 'b');

		// print to console
		System.out.println("\n\nExample 2 : replace('a', 'b')\n");
		System.out.println("The original string is : " 
				+ testStr2);
		System.out.println("The replaced string is : " 
				+ replacedStr2);
	}
}

Output:

Example 1 : replace('p', 'v') 

The original string is : penguins are rare species
The replaced string is : venguins are rare svecies


Example 2 : replace('a', 'b') 

The original string is : all human being born with special talent
The replaced string is : bll humbn being born with specibl tblent

 

Example 2: replace() method for char sequence (or substring)

  • Java program to showcase how to replace old-character-sequence (or sub-string) with new-character-sequence (or sub-string) using String’s replace() method

StringReplaceMethod2.java

package in.bench.resources.string.methods;

public class StringReplaceMethod2 {

	public static void main(String[] args) {

		// Example 1: test string
		String testStr1 = "English is a easy language "
				+ "but Java is super cool language";

		// replace all "language" with "medium"
		String replacedStr1 = 
				testStr1.replace("language", "medium");

		// print to console
		System.out.println("Ex 1 : replace(\"language\","
				+ " \"medium\") \n");
		System.out.println("Original string : " + testStr1);
		System.out.println("Replaced string : " + replacedStr1);


		// Example 2: test string
		String testStr2 = 
				"all human being born with special talent";

		// replace all "talent" with "skill"
		String replacedStr2 = testStr2.replace("talent", "skill");

		// print to console
		System.out.println("\n\nEx 2 : replace(\"talent\","
				+ " \"skill\") \n");
		System.out.println("Original string : " + testStr2);
		System.out.println("Replaced string : " + replacedStr2);
	}
}

Output:

Ex 1 : replace("language", "medium") 

Original string : 
	English is a easy language but Java is super cool language
Replaced string : 
	English is a easy medium but Java is super cool medium


Ex 2 : replace("talent", "skill") 

Original string : all human being born with special talent
Replaced string : all human being born with special skill

 

Example 3: replaceAll() method for substring using regex

  • Java program to showcase how to replace all old-char-sequence (or sub-string) with new-char-sequence (or sub-string) using String’s replaceAll() method
  • Note: this uses regular expression for pattern matching

StringReplaceAllMethod.java

package in.bench.resources.string.methods;

public class StringReplaceAllMethod {

	public static void main(String[] args) {

		// Example 1: test string
		String testStr1 = "English is a easy language "
				+ "but Java is super cool language";

		// replace all "language" with "medium"
		String replacedStr1 = testStr1.replaceAll("l[a-z]*e",
				"medium");

		// print to console
		System.out.println("Ex 1 : replaceAll(\"l[a-z]*e\","
				+ " \"medium\") \n");
		System.out.println("Original string : " + testStr1);
		System.out.println("Replaced string : " + replacedStr1);


		// Example 2: test string
		String testStr2 = 
				"all human being born with special talent";

		// replace all "space" with "-"
		String replacedStr2 = testStr2.replaceAll("\\s", "-");

		// print to console
		System.out.println("\n\nEx 2 : replaceAll(\"\\s\","
				+ " \"-\") \n");
		System.out.println("Original string : " + testStr2);
		System.out.println("Replaced string : " + replacedStr2);

		// Example 3: replaceAll 'l' characters with 'p'
		String testChar = "All izz well";

		// replace all "l" with "p"
		String replacedChar = testChar.replaceAll("l", "p");

		// print to console
		System.out.println("\n\nEx 3 : replaceAll(\"l\","
				+ " \"p\") \n");
		System.out.println("Original string : " + testChar);
		System.out.println("Replaced string : " + replacedChar);
	}
}

Output:

Ex 1 : replaceAll("l[a-z]*e", "medium") 

Original string : 
	English is a easy language but Java is super cool language
Replaced string : 
	English is a easy medium but Java is super cool medium


Ex 2 : replaceAll("\s", "-") 

Original string : all human being born with special talent
Replaced string : all-human-being-born-with-special-talent


Ex 3 : replaceAll("l", "p") 

Original string : All izz well
Replaced string : App izz wepp

 

Example 4: replaceFirst() method for substring using regex

  • Java program to showcase how to replace first old-char-sequence (or sub-string) with new-char-sequence (or sub-string) using String’s replaceFirst() method

Note:

  • this uses regular expression for pattern matching and
  • it is other variant of replaceAll() method –> which replaces of 1st occurrence matching string

StringReplaceFirstMethod.java

package in.bench.resources.string.methods;

public class StringReplaceFirstMethod {

	public static void main(String[] args) {

		// Example 1: test string
		String testStr1 = "AR Rahman is Oscar winner of 2009";

		// replace first occurrence of "is" with "was"
		String replacedStr1 = testStr1.replaceFirst("is", "was");

		// print to console
		System.out.println("Ex 1 : replaceFirst(\"is\","
				+ " \"was\") \n");
		System.out.println("Original string : " + testStr1);
		System.out.println("Replaced string : " + replacedStr1);


		// Example 2: test string
		String testStr2 = "Bench Resources Net";

		// replace first occurrence "space" with ""
		String replacedStr2 = testStr2.replaceFirst("\\s", "");

		// print to console
		System.out.println("\n\nEx 2 : replaceFirst(\"\\s\","
				+ " \"\") \n");
		System.out.println("Original string : " + testStr2);
		System.out.println("Replaced string : " + replacedStr2);

		// Example 3: 
		// replace first occurrence 'A' characters with 'a'
		String testChar = "All izz well";

		// replace all "A" with "a"
		String replacedChar = testChar.replaceFirst("A", "a");

		// print to console
		System.out.println("\n\nEx 3 : replaceFirst(\"A\","
				+ " \"a\") \n");
		System.out.println("Original string : " + testChar);
		System.out.println("Replaced string : " + replacedChar);
	}
}

Output:

Ex 1 : replaceFirst("is", "was") 

Original string : AR Rahman is Oscar winner of 2009
Replaced string : AR Rahman was Oscar winner of 2009


Ex 2 : replaceFirst("\s", "") 

Original string : Bench Resources Net
Replaced string : BenchResources Net


Ex 3 : replaceFirst("A", "a") 

Original string : All izz well
Replaced string : all izz well

 

Hope, you found this article very helpful. If you any suggestion or want to contribute any other way or tricky situation you faced during Interview hours, then share with us. We will include that code here.

 

References:

 

Happy Coding !!
Happy Learning !!

Java: String split() method
Java: String regionMatches() method