String Replace in Java

We have worked with Strings and discussed a lot of operations in recent posts. Many times, we encounter a situation when we want to replace a specific character or string with another. We can replace the character or string by use of java replace method.

string replace in java

string replace() method uses to replace the content of a String with other content. Through replace() function, we can replace the old character or string with the new characters or strings. Java provides the replace() method that overloaded in the string class. Let’s discuss how to use the java replace() method and replace characters in string java.

The replace() is overloaded method in String class. It has 4 types:

1. replace(char oldCharacterName, char newCharacterName);
2. replace(charSequence OldCharSequence, charSequence newCharSequence);
3. replaceFirst(String oldSubstringName, String newSubstringName);
4. replaceAll(String oldSubstringName, String newSubstringName);

5. Difference between replace() and replaceAll()

1. replace(char oldCharacterName, char newCharacterName)

This method utilizes to replace the old character with a new character. It replaces all the occurrence of old characters with new characters. Also, Its return type is String. It takes two parameters of char types. If the old character doesn’t find it in the current String, then the String remains the same as it is. This method doesn’t change anything in the String.

stringName.replace(oldCharacter, newCharacter)

stringName: The name of the String in which you want to replace the old characters with new characters.
oldCharacter: The character which you want to replace in the String.
newCharacter: The character which will be used to replace the old character in the String.

public class StringExample
{
	public static void main(String[] args) 
	{		
		String str1 = "JavaGoal website";
		System.out.println("Before replace: "+str1);
		// Replace all the occurrence of 'a' with 'w'
		String str2 = str1.replace('a', 'w');
		System.out.println("After replace: "+str2);
		
		String str3 = "Hi Java";
		System.out.println("Before replace: "+str3);
		// Replace all the occurrence of 'r' with 'N'
		String str4 = str3.replace('r', 'N');
		// But 'r' is not presented so it remain same
		System.out.println("After replace: "+str4);
	}
}

Output: Before replace: JavaGoal website
After replace: JwvwGowl website
Before replace: Hi Java
After replace: Hi Java

2. replace(charSequence OldCharSequence, charSequence newCharSequence)

This method employs to replace the old substring with a new substring. It replaces all the occurrences of an old substring with a new substring. Its return type is String. Also, It takes two parameters of CharSequence types. It means you can replace a group of characters. If the old substring doesn’t find in the current string, then the String remains the same as it is. This method doesn’t change anything in the String.

stringName.replace(oldCharSequence, newCharSequence)

stringName: The name of string in which you want to replace the old subString with a new Substring.
oldCharSequence: The Substring which you want to replace in the String.
newCharSequence: The Substring will be used to replace the old Substring in the String.

public class StringExample
{
	public static void main(String[] args) 
	{		
		String str1 = "aabbcc aa bb cc abcaa";
		System.out.println("Before replace: "+str1);
		// Replace all the substring of "aa" with "zz"
		String str2 = str1.replace("aa", "zz");
		System.out.println("After replace: "+str2);
		
		String str3 = "Hi JavaGoal.com";
		System.out.println("Before replace: "+str3);
		// Replace all the substring of "aa" with "zz"
		String str4 = str3.replace("aa", "zz");
		// But 'aa' is not presented so it remain same
		System.out.println("After replace: "+str4);
	}
}

Output: Before replace: aabbcc aa bb cc abcaa
After replace: zzbbcc zz bb cc abczz
Before replace: Hi JavaGoal.com
After replace: Hi JavaGoal.com

3. replaceFirst(String regex, String newSubstringName):

This method applies to replace the regex with a new substring. You can directly provide any string without the regex condition. It replaces first the occurrence of substring(which matched with regex) with a new substring. Its return type is String. It takes two parameters of String types.

NOTE: If regex doesn’t find any string in the current string, then the string remains the same as it is. This method doesn’t change anything in the string.

stringName.replaceFirst(regex, newSubstring)

stringName: The name of string in which you want to replace the old subString with a new Substring.
regex: The regular expression to which this string is to be matched
newSubstring: This Substring will be used to replace the Substring that matched with regex condition.

public class ReplaceFirstExample
{
   public static void main(String args[])
   {
	   String str = "Hi Java, Let's see the Java website";
	   // It will replace only first occurrence of "Java"  
	   System.out.println(str.replaceFirst("Java", "JavaGoal"));
	   
	   //It will replace whitespace with '#'
	   System.out.println(str.replaceFirst("\\s", "#"));
   }
}

Output: Hi JavaGoal, Let’s see the Java website
Hi#Java, Let’s see the Java website

4. replaceAll(String regex, String newSubstringName)

This method works to replace the old substring with a new substring. It replaces all the occurrences of an old substring with a new substring. You can give any regex condition in the first parameter. All the substring that matched with condition replaced by the newSubString. Its return type is String. It takes two parameters of String types.

stringName.replaceAll(regex, newSubstringName)

stringName: The name of string in which you want to replace the old subString with a new Substring.
regex: The regular expression to which this string is to be matched.
newSubstringName: Here, the Substring will be used to replace the Substring that matched with regex condition.

public class ReplaceFirstExample
{
   public static void main(String args[])
   {
	   String name1 = "WELCOME TO JAVAGoal website";  
	   name1 = name1.replaceAll("(.*)JAVA", "KNOWLEDGE Base");
	   System.out.println("After replace = "+name1); 	
	   
	   String name2 = "WELCOME TO JAVAGoal website";  
	   name2 = name2.replaceAll("JAVA(.*)", "KNOWLEDGE Base");
	   System.out.println("After replace= "+name2); 	
	   
	   String str = "Hi Java, Let's see the Java website";
	   //It will replace all whitespace with '#'
	   System.out.println(str.replaceAll("\\s", "#"));
   }
}

Output: After replace = KNOWLEDGE BaseGoal website
After replace= WELCOME TO KNOWLEDGE Base
Hi#Java,#Let’s#see#the#Java#website

Difference between replace() and replaceAll()

As you have seen the working of replace() method and replaceAll() method. Both methods replace all the occurrences of the string. But many programmers don’t the major difference between these methods.

The replace() method can take either two chars or two CharSequences as parameters and replace all occurrences of char or String. But the replaceAll() method can take only the regex String as a parameter and replaces all the substring which matches with the given regex. So you have to use the correct method at the correct place.

Suppose if you just want to replace a simple substring(You are not using regex) then you should use replace() method because the replaceAll() method calls the java.util.regex.Pattern.compile() method each time it is called even if the given argument is not a regular expression. This creates a performance issue and can introduce a bug in the code.

Leave a Comment