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的区别

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);

public class Main {

    public static void main(String[] args) {
	    String strTmp = new String("BBBBYYYYYY");

	    strTmp = strTmp.replaceAll("\\D","Y");
	    System.out.println(strTmp);
        strTmp = strTmp.replaceAll("Y","N");
        System.out.println(strTmp);

        strTmp = strTmp.replace("N","C");
        System.out.println(strTmp);

        strTmp = strTmp.replaceFirst("\\D","q");
        System.out.println(strTmp);
    }
}

 结果:

YYYYYYYYYY
NNNNNNNNNN
CCCCCCCCCC
qCCCCCCCCC

 

 

 

 

你可能感兴趣的:(Java中替换字符串中特定字符,replaceAll,replace,replaceFirst的区别)