In Java String there are three types of Replace method. They are -
- replace ()
- replaceAll ()
- replaceFirst ()
All these methods are used to replace characters in your string with some characters as you wish. So What's the difference between replaceAll, replaceFirst and replace in Java String? Let us look at each of these methods in detail with examples:
- replace() Method:
There are two replace() methods in Java, they are -
- public String replace(char oldChar,char newChar):
This method returns a String resulting from replacing all occurances of oldChar argument in this string with the newChar.
Example:
public class Example{
public static void main(String args[]) {
String s1 = new String("I Love Solution");
System.out.println("Original String is ': " + s1);
System.out.println("String after replacing 'o' with 'e': " + s1.replace('o', 'e'));
}
}
Output:
Original String is ': I Love Solution
String after replacing 'o' with 'e': I Leve Selutien
- public String replace(CharSequence target, CharSequence replacement):
This method Replaces each substring of this string that matches the literal target sequence specified in the method with the specified literal replacement sequence specified in the method. The replacement proceeds from the beginning of the string to the end, for example, replacing "ss" with "j" in the string "sss" will result in "js" rather than "sj".
Example:
public class Example{
public static void main(String args[]) {
String s1 = new String("I Love World");
System.out.println("Original String is ': " + s1);
System.out.println("String after replacing 'love' with 'like': " + s1.replace("Love", "Like"));
}
}
Output:
Original String is ': I Love World
String after replacing 'love' with 'like': I Like World
- replaceAll() Method:
The syntax for replaceAll() Method is-
public String replaceAll(String regex, String replacement)
This method replaces each substring of this string that matches the given regular expression with the given replacement String in parameter.
Example:
public class Example{
public static void main(String args[]) {
String s1 = "We gives you solution to all your technical needs";
//replace all white spaces with (-)
String s2 = s1.replaceAll("\\s", "-");
System.out.println(s2);
}
}
Output:
We-gives-you-solution-to-all-your-technical-needs
- replaceFirst() Method:
The syntax for replaceFirst() Method is-
public String replaceFirst(String regex, String replacement)
This method replaces the first substring of this string that matches the given regular expression with the given replacement.
Example:
public class Example{
public static void main(String args[]) {
String s1 = "We give you solution to all your technical needs";
//replace first white space with (-)
String s2 = s1.replaceFirst("\\s", "-");
System.out.println(s2);
}
}
Output:
We-give you solution to all your technical needs