呵呵,你再看看String 的 replaceAll文档,虽然两个参数都是String,但不是"源" 和"目的"
的关系.第一个String 是regex(regular expression) 表达式,解释起来很麻烦,建议去看API,在SUN的forum上有人提供了一个算法实现字符串替换的,你可以用:
/**
* Retuns a String that is the result of transforming "targetString",
* replacing the ocurrences of "toReplace" by the String "replaceBy".
*
* @param targetString String where apply the transformation
* @param toReplace substring to be replaced
* @param replaceBy substring to replace the ocurrences
* of "toReplace"
* @return the String resultant of the transformation
*/
public static String replaceString(String targetString,
String toReplace,
String replaceBy) {
StringBuffer result = new StringBuffer(targetString);
int i = 0;
int j = 0;
int toRepLength = toReplace.length();
if (toRepLength > 0) {
int lengthDecrease = toRepLength - replaceBy.length();
while ( (i = targetString.indexOf(toReplace, i)) != -1) {
result.replace(i - j, i - j + toRepLength, replaceBy);
i += toRepLength;
j += lengthDecrease;
}
}
return result.toString();
}
的关系.第一个String 是regex(regular expression) 表达式,解释起来很麻烦,建议去看API,在SUN的forum上有人提供了一个算法实现字符串替换的,你可以用:
/**
* Retuns a String that is the result of transforming "targetString",
* replacing the ocurrences of "toReplace" by the String "replaceBy".
*
* @param targetString String where apply the transformation
* @param toReplace substring to be replaced
* @param replaceBy substring to replace the ocurrences
* of "toReplace"
* @return the String resultant of the transformation
*/
public static String replaceString(String targetString,
String toReplace,
String replaceBy) {
StringBuffer result = new StringBuffer(targetString);
int i = 0;
int j = 0;
int toRepLength = toReplace.length();
if (toRepLength > 0) {
int lengthDecrease = toRepLength - replaceBy.length();
while ( (i = targetString.indexOf(toReplace, i)) != -1) {
result.replace(i - j, i - j + toRepLength, replaceBy);
i += toRepLength;
j += lengthDecrease;
}
}
return result.toString();
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货