0
点赞
收藏
分享

微信扫一扫

Java replace()方法

泠之屋 2022-02-22 阅读 75

1. 来源

2.语法

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

3.作用

4.示例

public static void main(String[] args){
	String str = "helloworld";
	System.out.println("原字符串:"+ str);
	System.out.println("新字符串:"+ str.replace("l", "L"));
}
原字符串: helloworld
新字符串: heLLoworLd
举报

相关推荐

0 条评论