1. 来源
replace()方法是来自于Java1.8中String类提供的的一个方法
2.语法
oldChar: 原字符
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;
}
3.作用
通过使用newChar字符替换掉原本字符串中的oldChar字符,并生成替换后新的字符串
4.示例
public static void main(String[] args){
String str = "helloworld";
System.out.println("原字符串:"+ str);
System.out.println("新字符串:"+ str.replace("l", "L"));
}
编译运行后结果:
原字符串: helloworld
新字符串: heLLoworLd