java字符替换 之 replace,replaceAll,replaceFirst

来源:互联网 发布:mac系统字体设置 编辑:程序博客网 时间:2024/05/18 03:23

replaceAll,replaceFirst的区别:

1)replace的参数是char和CharSequence,即可以支持字符的替换,也支持字符串的替换(CharSequence即字符串序列的意思,说白了也就是字符串);2)replaceAll的参数是regex,即基于规则表达式的替换,比如,可以通过replaceAll("\\d", "*")把一个字符串所有的数字字符都换成星号; 1、String java.lang.String.replace(CharSequence target, CharSequence replacement)

Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.

The replacement proceeds from the beginning of the string to the end, for example, replacing "aa" with "b" in the string "aaa"

will result in "ba" rather than "ab".

详细可以看API,代码:

public class StringTest {public static String replace(String myString){//替换字符串中的所以的XString  str=myString.replace("x","y");return str;}public static String replaceAll(String myString){//替换字符串中的所以的XString  str=myString.replaceAll("x","y");return str;}public static String replaceFirst(String myString){//替换第一个字符串中的第一个XString  str=myString.replaceFirst("x","y");return str;}public static void main(String[] args) {//1)replace的参数是char和CharSequence,即可以支持字符的替换,也支持字符串的替换(CharSequence即字符串序列的意思,说白了也就是字符串);//2)replaceAll的参数是regex,即基于规则表达式的替换,比如,可以通过replaceAll("\\d", "*")把一个字符串所有的数字字符都换成星号; //replace("x","y");//这个是替换在字符串中把第一次出现的x替换成y  replace("要替换的字符串", "新的字符串")String  str="axbxcxdxexjxyx";String newStr=replace(str);String newStr1=replaceAll(str);String newStr2=replaceFirst(str);System.out.println("replace     :"+newStr+"\r"+"replaceAll  :"+newStr1+"\r"+"replaceFirst:"+newStr2);}}

原创粉丝点击