Java教程

Java String replace()

java String replace()方法返回一个字符串,该字符串将所有旧的char或CharSequence替换为新的char或CharSequence。
从JDK 1.5开始,引入了新的replace()方法,使您可以替换一系列char值。

内部实现

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;
}

签名

java字符串中有两种替换方法。
public String replace(char oldChar, char newChar)

public String replace(CharSequence target, CharSequence replacement)
自JDK 1.5起添加了第二种替换方法。

参数

oldChar : 旧字符
newChar : 新字符
target: 目标字符序列
replacement: 字符替换序列

返回

替换的字符串

Java replace(oldChar,newChar)方法示例

public class ReplaceExample1{
    public static void main(String args[]){
        String s1="lidihuo is a very good website";
        String replaceString=s1.replace('i','e');
        System.out.println(replaceString);
    }
}
ledehuo es a very good websete

String replace(CharSequence target, CharSequence replacement)方法示例

public class ReplaceExample2{
    public static void main(String args[]){
        String s1="my name is khan my name is java";
        String replaceString=s1.replace("is","was");
        System.out.println(replaceString);
    }
}
my name was khan my name was java

Java String replace()方法示例3

public class ReplaceExample3 {
    public static void main(String[] args) {
        String str = "oooooo-hhhh-oooooo";
        String rs = str.replace("h","s");
        System.out.println(rs);
        rs = rs.replace("s","h");
        System.out.println(rs);
    }
}
oooooo-ssss-oooooooooooo-hhhh-oooooo
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4