`
个人专属
  • 浏览: 65817 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

字符串替换

JDK 
阅读更多
最好还是用我们自己实现的替换字符串的方法来做(JDK 1.4 之前找的代码):

// ------------------------------------ 字符串处理方法
// ----------------------------------------------

/**
* 将字符串 source 中的 oldStr 替换为 newStr, 并以大小写敏感方式进行查找
*
* @param source
* 需要替换的源字符串
* @param oldStr
* 需要被替换的老字符串
* @param newStr
* 替换为的新字符串
*/
public static String replace(String source, String oldStr, String newStr) {
return replace(source, oldStr, newStr, true);
}

/**
* 将字符串 source 中的 oldStr 替换为 newStr, matchCase 为是否设置大小写敏感查找
*
* @param source
* 需要替换的源字符串
* @param oldStr
* 需要被替换的老字符串
* @param newStr
* 替换为的新字符串
* @param matchCase
* 是否需要按照大小写敏感方式查找
*/
public static String replace(String source, String oldStr, String newStr,
boolean matchCase) {
if (source == null) {
return null;
}
// 首先检查旧字符串是否存在, 不存在就不进行替换
if (source.toLowerCase().indexOf(oldStr.toLowerCase()) == -1) {
return source;
}
int findStartPos = 0;
int a = 0;
while (a > -1) {
int b = 0;
String str1, str2, str3, str4, strA, strB;
str1 = source;
str2 = str1.toLowerCase();
str3 = oldStr;
str4 = str3.toLowerCase();
if (matchCase) {
strA = str1;
strB = str3;
} else {
strA = str2;
strB = str4;
}
a = strA.indexOf(strB, findStartPos);
if (a > -1) {
b = oldStr.length();
findStartPos = a + b;
StringBuffer bbuf = new StringBuffer(source);
source = bbuf.replace(a, a + b, newStr) + "";
// 新的查找开始点位于替换后的字符串的结尾
findStartPos = findStartPos + newStr.length() - b;
}
}
return source;
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics