java字符替换 之 replace,replaceAll,replaceFirst

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){
		//替换字符串中的所以的X
		String  str=myString.replace("x","y");

		return str;
	}
	public static String replaceAll(String myString){
		//替换字符串中的所以的X
		String  str=myString.replaceAll("x","y");

		return str;
	}
	public static String replaceFirst(String myString){
		//替换第一个字符串中的第一个X
		String  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);
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值