一、replace(String old,String new)
功能:將字符串中的所有old子字符串替換成new字符串
示例
String s="Hollow world!"; System.out.println(s); System.out.println(s.replace("o", "#")); /* * 結果:Hollow world! * H#ll#w w#rld! */
二、replaceAll(String arg0, String arg1)
其中字符串表示arg0為正則表達式
功能
將字符串中符合正則表達式arg0的所有子字符串,替換成字符串arg1
示例
String s="Hollow world!"; System.out.println(s); /** * 正則表達式中.表示除換行符以外的任意字符 * 所以s.replaceAll(".", "#")的意思是 * 將所有字符替換成# */ System.out.println(s.replaceAll(".", "#")); /* * 結果:Hollow world! * ############# */
三、replaceFisrst(String arg0, String arg1)
其中字符串表示arg0為正則表達式
功能
將字符串中符合正則表達式arg0的第一個子字符串,替換成字符串arg1
示例
String s="Hollow world!"; System.out.println(s); /** * 正則表達式中.表示除換行符以外的任意字符 * 所以s.replaceFirst(".", "#")的意思是 * 將第一個字符替換成# */ System.out.println(s.replaceFirst(".", "#")); /* * 結果:Hollow world! * #ollow world! */
注意:這三個方法返回替換后的字符串,原字符串不發生變化