How to replace a String in Java? | replace() vs replaceAll() vs replaceFirst()

In the last tutorial, we have learned how to find the length of the string in java. In this tutorial, we will learn how to replace a string in java. The replace() method of String class is used to replace all the occurrences of an old character in this string with a new character. 

Syntax: The syntax of the string replace() method is given below:

public String replace(char oldChar, char newChar)
Here, oldChar specifies the characters to be replaced by the character specified by newChar.

Example of Java String replace() Method:


class StringReplace{
	public static void main(String args[]){
		String str1  = "Streng Tutoreal";
		//replacing e with i.
		System.out.println(str1.replace('e', 'i'));
	}
}

Output:

String Tutorial 


replaceAll() method in Java

This method returns a String replaces each substring with this string that matches given regular expression with the given replacement.

Syntax: The syntax of the replaceAll() method is given below:

public String replaceAll(String regex, String replacement)


Example of replaceAll() method in Java:


class StringReplace{
	public static void main(String args[]){
		String str1  = "String Tutorial is javastudypoint";
		//replacing all the occurencres of is with by.
		System.out.println(str1.replaceAll("is", "by"));
		//removing all the whitespaces.
		System.out.println(str1.replaceAll("\\s",""));
	}
}

Output:

String Tutorial by javastudypoint
StringTutorialisjavastudypoint.

Remember that, it throws PatternSyntaxException if the regular expression syntax is invalid. Let's see the example.

class StringReplace{
	public static void main(String args[]){
		String str1  = "String Tutorial is javastudypoint";
		//throws PatternSyntaxException
		System.out.println(str1.replaceAll("[", ""));
	}
}

Output:
replace a string in java



replaceFirst() method in Java

This method is used to replaces the first substring of this string that matches the given regular expression with the given replacement. It throws PatternSyntaxException if the regular expression is invalid.

Syntax: The syntax of the replaceFirst() method is given below:

public String replaceFirst(String regex, String replacement)


Example of replaceFirst() method in Java:


class StringReplace{
	public static void main(String args[]){
		String str1  = "String Tutorial by author";
		//repalces first occuerence of author with Prashant.
		System.out.println(str1.replaceFirst("author","Prashant"));
	}
}

Output:

String Tutorial by Prashant

How to replace a String in Java? | replace() vs replaceAll() vs replaceFirst() How to replace a String in Java? | replace() vs replaceAll() vs replaceFirst() Reviewed by Prashant Srivastava on January 04, 2020 Rating: 5

No comments:

Powered by Blogger.