Java String replace() Method Example

The replace() method has two forms. The first replaces all occurrences of one character in the invoking string with another character. It has the following general form:
String replace(char original, char replacement)
Here, original specifies the character to be replaced by the character specified by replacement. The resulting string is returned. For example,
String s = "Hello".replace('l', 'w');
puts the string "Hewwo" into s.
The second form of replace() replaces one character sequence with another. It has this general form:
String replace(CharSequence original, CharSequence replacement)

Java String replace() Method Example

This is a complete example to demonstrate the usage of replace() methods.
public class ReplaceExample {
    public static void main(String[] args) {
        String str = "javaguides";
        String subStr = str.replace('a', 'b');
        System.out.println("replace char 'a' with char 'b' from given string : " + subStr);
        subStr = str.replace("guides", "tutorials");
        System.out.println("replace guides with tutorials from given string : " + subStr);
        subStr = str.replaceAll("[a-z]", "java");
        System.out.println(subStr);
        subStr = str.replaceFirst("[a-z]", "java");
        System.out.println(subStr);
    }
}

Output:
replace char 'a' with char 'b' from given string: jbvbguides replace guides with tutorials from given string: javatutorials javajavajavajavajavajavajavajavajavajava javaavaguides 

Reference



Comments