📅  最后修改于: 2020-09-26 05:58:46             🧑  作者: Mango
Java 字符串 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)
and
public String replace(CharSequence target, CharSequence replacement)
从JDK 1.5开始添加了第二种替换方法。
oldChar:旧字符
newChar:新字符
target:目标字符序列
替换:字符的替换顺序
替换字符串
public class ReplaceExample1{
public static void main(String args[]){
String s1="javatpoint is a very good website";
String replaceString=s1.replace('a','e');//replaces all occurrences of 'a' to 'e'
System.out.println(replaceString);
}}
"jevetpoint is e very good website
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");//replaces all occurrences of "is" to "was"
System.out.println(replaceString);
}}
my name was khan my name was java
public class ReplaceExample3 {
public static void main(String[] args) {
String str = "oooooo-hhhh-oooooo";
String rs = str.replace("h","s"); // Replace 'h' with 's'
System.out.println(rs);
rs = rs.replace("s","h"); // Replace 's' with 'h'
System.out.println(rs);
}
}
oooooo-ssss-oooooo
oooooo-hhhh-oooooo