Java String replace(), replaceFirst() & replaceAll() Method EXAMPLE

Java String has three types of Replace method
  1. replace
  2. replaceAll
  3. replaceFirst.
With the help of these you can replace characters in your string. Lets study each in details:

1. Java String replace() Method

Description:
This Java method returns a new string resulting from replacing every occurrence of characters with a new characters
Syntax:
public Str replace(char oldC, char newC)
Parameters:
oldCh − old character.
newCh − new character.
Return Value
This fucntion returns a string by replacing oldCh with newCh.
Example 1
public class Guru99Ex1 {
    public static void main(String args[]) {
        String S1 = new String("the quick fox jumped");
        System.out.println("Original String is ': " + S1);
        System.out.println("String after replacing 'fox' with 'dog': " + S1.replace("fox", "dog"));
        System.out.println("String after replacing all 't' with 'a': " + S1.replace('t', 'a'));

    }
}
Output:
Original String is ': the quick fox jumped
String after replacing 'fox' with 'dog': the quick dog jumped
String after replacing all 't' with 'a': ahe quick fox jumped

2.Java String Replaceall()

Description
The java string replaceAll() method returns a string replacing all the sequence of characters matching regular expression and replacement string.
Signature:
public Str replaceAll(String regex, String replacement)  
Parameters:
regx: regular expression
replacement: replacement sequence of characters
Example 2
public class Guru99Ex2 {
    public static void main(String args[]) {
        String str = "Guru99 is a site providing free tutorials";
        //remove white spaces
        String str2 = str.replaceAll("\\s", "");
        System.out.println(str2);
    }
}
Output:
Guru99isasiteprovidingfreetutorials

3. Java - String replaceFirst() Method

Description
The method replaces the first substring of the given string which matches that regular expression.
Syntax
public Str replaceFirst(String rgex, String replacement)
Parameters
rgex − the regular expression to which given string need to matched.
replacement − the string that replaces regular expression.
Return Value
This method returns resulting String as an output.
Example 3:
public class Guru99Ex2 {
    public static void main(String args[]) {
        String str = "This website providing free tutorials";
        //Only Replace first 's' with '9' 
        String str1 = str.replaceFirst("s", "9");
        System.out.println(str1);
    }
}
Output:
Thi9 website providing free tutorials

No comments:

Post a Comment