Java中替换字符串中特定字符,replaceAll,replace,replaceFirst的区别

  • 使用“;”替换过字符串中的“,”。

 

public class Test01 {
public static void main(String[] args) {
String number = "123,456,5234,52345,63456,7456,7";
String newNumber = number.replace(",", ";");
System.out.println(newNumber);
}

}

 

结果:

123;456;5234;52345;63456;7456;7

 

 

  • replaceAll,replace,replaceFirst的区别

public class Test01 {
public static void main(String[] args) {

//replaceAll,replace,replaceFirst的区别
String strTmp = new String("BBBBBBBYYYYYYY");
//replaceAll支持正则表达式和字符替换
strTmp = strTmp.replaceAll ("\\D", "Y");
System.out.println(strTmp);
strTmp = strTmp.replaceAll ("Y", "N");
System.out.println(strTmp);
//replace支持字符和字符串替换
strTmp = strTmp.replace("N", "C");
System.out.println(strTmp);
//只替换第一个字符
strTmp = strTmp.replaceFirst("\\D", "q");
System.out.println(strTmp);
}

}

 

结果:

 

posted @ 2019-04-03 10:12  刘建军  阅读(92124)  评论(0编辑  收藏  举报