Java String Replace

时间:2020-02-23 14:35:14  来源:igfitidea点击:

Java String replace方法将所有旧的char或者旧的charsequence替换为新的char sequence并返回新字符串。
如果在字符串中没有替换,则会返回相同的字符串。

假设我们需要将"onitad"转换为"javatwoblog",我们可以简单地使用以下语法。

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

语法

字符串替换方法有两个超载版本。

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

例子

让我们在简单的例子的帮助下了解。

package org.igi.theitroad;
 
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);
	}
}

运行上面的程序时,我们将得到以下输出:

HelloWorld converted to : HellnWnrld

上面的程序将调用公共字符串替换(Char OldChar,Char NewChar)版本的替换方法。

package org.igi.theitroad;
 
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);
 
	}
}

运行上面的程序时,我们将得到以下输出:

How HashSet works in java

上面的程序将调用公共字符串替换(Char OldChar,Char NewChar)版本的替换方法。

内部实现

公共字符串替换(Char Oudchar,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;
    }

正如我们所看到的,上面的方法发现首次出现OldChar,然后找到剩余的字符串并用NewChar替换它。

公共字符串替换(CharSequence目标,CharSequence更换)

/**
     * 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()));
    }

以上代码使用模式和匹配器来替换字符串。