String replaceAll() Method

      No Comments on String replaceAll() Method




String replaceAll() method is used to replace each substring of a string that matches the given regular expression with the given replacement.

Signature of replaceAll() Method:
String replaceAll(String regex, String replacement)

Suppose, there is a STring as given below.

String str = “Hello, this is India”;

Now, in this String of you want to replace “is” (all occurrences) with String “are”, then you can use replaceAll() method.

After replacement, the final String will be as below:

String newStr = “Hello, there are India”;

So, all occurrences of “is” got replaced with “are”.

Let’s take an example of this.

Example : String replaceAll() method
package com.masterjavatutorial;
public class TestExample {
    public static void main(String[] args) {
        String str = "This is a test program";
        String newStr = str.replaceAll("is", " hello "); 
        System.out.println("String str after replacement = "+newStr); 
    }
}

Output of the above program is as below:

String str after replacement = Th hello   hello  a test program