Java String Replace

Java String replace method replaces all occurrences of old char to new char or old CharSequence to new CharSequence and return new String. If there is nothing to replace in the String, it will return same String.

Let’s say you need to convert "Java2blog" to "JavaTwoblog", you can simply use below syntax.

String result=input.replace("2", "Two");

Syntax

There are two overloaded version of String’s replace method.

public String replace(char oldChar, char newChar)
and 
public String replace(CharSequence target, CharSequence replacement)

Example

Let’s understand with the help of Simple example.

package org.arpit.java2blog;

public class JavaStringReplaceMain {

    public static void main(String[] args) {
        String input="HelloWorld";
        String result=input.replace('o', 'n'); // This code will replace 'o' to 'n' in String
        System.out.println("HelloWorld converted to : "+result);
    }
}

When you run above program, you will get below output:

HelloWorld converted to : HellnWnrld

Above program will call public String replace(char oldChar, char newChar) version of replace method.

package org.arpit.java2blog;

public class JavaStringReplaceMain {

    public static void main(String[] args) {
        String input="How HashMap works in java";
        String result=input.replace("Map", "Set");
        System.out.println(result);

    }
}

When you run above program, you will get below output:

How HashSet works in java

Above program will call public String replace(char oldChar, char newChar) version of replace method.

Internal implementation

public String replace(char oldChar, char newChar)

 
 /**
     * Returns a string resulting from replacing all occurrences of
     * {@code oldChar} in this string with {@code newChar}.
     * If the character {@code oldChar} does not occur in the
     * character sequence represented by this {@code String} object,
     * then a reference to this {@code String} object is returned.
     * Otherwise, a {@code String} object is returned that
     * represents a character sequence identical to the character sequence
     * represented by this {@code String} object, except that every
     * occurrence of {@code oldChar} is replaced by an occurrence
     * of {@code newChar}.
     * Examples:
     * "mesquite in your cellar".replace('e', 'o')
     *         returns "mosquito in your collar"
     * "the war of baronets".replace('r', 'y')
     *         returns "the way of bayonets"
     * "sparring with a purple porpoise".replace('p', 't')
     *         returns "starring with a turtle tortoise"
     * "JonL".replace('q', 'x') returns "JonL" (no change)
     *
     * @param   oldChar   the old character.
     * @param   newChar   the new character.
     * @return  a string derived from this string by replacing every
     *          occurrence of {@code oldChar} with {@code newChar}.
     */
public String replace(char oldChar, char newChar) {
        if (oldChar != newChar) {
            int len = value.length;
            int i = -1;
            char[] val = value; /* avoid getfield opcode */

            while (++i < len) {
                if (val[i] == oldChar) {
                    break;
                }
            }
            if (i < len) {
                char buf[] = new char[len];
                for (int j = 0; j < i; j++) {
                    buf[j] = val[j];
                }
                while (i < len) {
                    char c = val[i];
                    buf[i] = (c == oldChar) ? newChar : c;
                    i++;
                }
                return new String(buf, true);
            }
        }
        return this;
    }

As you can see, above method finds first occurence of oldChar and then remaining string and replaces it with newChar.

public String replace(CharSequence target, CharSequence replacement)

 /**
     * Replaces each substring of this string that matches the literal target
     * sequence with the specified literal replacement sequence. The
     * replacement proceeds from the beginning of the string to the end, for
     * example, replacing "aa" with "b" in the string "aaa" will result in
     * "ba" rather than "ab".
     *
     * @param  target The sequence of char values to be replaced
     * @param  replacement The replacement sequence of char values
     * @return  The resulting string
     * @since 1.5
     */
    public String replace(CharSequence target, CharSequence replacement) {
        return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
                this).replaceAll(Matcher.quoteReplacement(replacement.toString()));
    }

Above code used Pattern and matcher to replace String.
That’s all about Java String replace method.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.