Java 字符串replace()
方法用于替换字符串,将所有旧 char 或 CharSequence 替换为新 char 或 CharSequence。
语法
Java 字符串类中有两种 replace() 方法。
public String replace(char oldChar, char newChar)
public String replace(CharSequence target, CharSequence replacement)
从 JDK 1.5 开始添加了第二个replace()
方法。
参数
- oldChar : 旧字符
- newChar : 新字符
- target:目标字符序列
- replacement:字符的替换顺序
返回值
替换后的字符串
异常
NullPointerException:如果替换或目标等于 null。
内部实现
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;
}
public String replace(CharSequence target, CharSequence replacement)
{
return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
this).replaceAll(Matcher.quoteReplacement(replacement.toString()));
}
方法示例1
文件名: ReplaceExample1.java
public class ReplaceExample1{
public static void main(String args[]){
String s1="yxjc123 is a very good website";
String replaceString=s1.replace('a','e');//将所有出现的'a'替换为'e'
System.out.println(replaceString);
}
}
输出:
yxjc123 is e very good website
方法示例2
文件名: ReplaceExample2.java
public class ReplaceExample2{
public static void main(String args[]){
String s1="my name is yxjc my name is java";
String replaceString=s1.replace("is","was");//将所有出现的"is"替换为"was"
System.out.println(replaceString);
}
}
输出:
my name was yxjc my name was java
方法示例3
文件名: ReplaceExample3.java
public class ReplaceExample3 {
public static void main(String[] args) {
String str = "oooooo-hhhh-oooooo";
String rs = str.replace("h","s"); // 将 'h' 替换为 's'
System.out.println(rs);
rs = rs.replace("s","h"); // 将 's' 替换为 'h'
System.out.println(rs);
}
}
输出:
oooooo-ssss-oooooo
oooooo-hhhh-oooooo
oooooo-hhhh-oooooo
方法示例4
当替换或目标为空时,replace() 方法会抛出 NullPointerException。下面的例子证实了这一点。
文件名: ReplaceExample4.java
public class ReplaceExample4
{
// 主方法
public static void main(String argvs[])
{
String str = "For learning Java, yxjc123 is a very good site.";
int size = str.length();
System.out.println(str);
String target = null;
// 用 yxjc123 替换 null。因此,引发了 NullPointerException。
str = str.replace(target, "yxjc123 ");
System.out.println(str);
}
}
输出:
For learning Java, yxjc123 is a very good site.
Exception in thread "main" java.lang.NullPointerException
at java.base/java.lang.String.replace(String.java:2142)
at ReplaceExample4.main(ReplaceExample4.java:12)
Exception in thread "main" java.lang.NullPointerException
at java.base/java.lang.String.replace(String.java:2142)
at ReplaceExample4.main(ReplaceExample4.java:12)