Java replace和replaceAll的区别
replace()和replaceAll()说明
java中replace方法主要用于替换字符串,他有两个参数
参数1:替换前的字符串
参数2:想要替换的字符串
replace基本用法
//需求:将字符串g改为d
public class test {
public static void main(String[] args) {
String str=" a b c g u h k j ";
str=str.replace("g","d");
System.out.println(str);
//-->a b c d u h k j
}
}
replace多层嵌套用法
//需求:将a替换为壹、b>贰、c>叁、g>肆、u>伍
public class test {
public static void main(String[] args) {
String str=" a b c g u h k j ";
str=str
.replace("a","壹")
.replace("b","贰")
.replace("c","叁")
.replace("g","肆")
.replace("u","伍");
System.out.println(str);
//-->壹 贰 叁 肆 伍 h k j
}
}
replace与replaceAll的区别
replaceAll的用法replace基本相同,不同的是replaceAll的第一个参数可以用正则表达(regex)
replaceAll使用说明
参数1:替换前的字符串 可以用正则表达
参数2:想要替换的字符串
//需求替换字符串内所有大小空格为一个、连接
public class test {
public static void main(String[] args) {
String str="a b c g u h k j";
//正则匹配所有空格,替换为、
str=str.replaceAll(" +","、");
System.out.println(str);
//-->a、b、c、g、u、h、k、j
}
}
实例2:更改邮箱地址
//需求:将邮箱中任意@xxxx. 字符串改为@gmail
public class test2 {
public static void main(String[] args) {
String str="203455278@qq.com";
String postBox = str.replaceAll("@.+\.","@gmail.");
System.out.println(postBox);
//-->203455278@gmail.com
}
}
希望当前文章对你的开发有所帮助~