转 /** * Replaces all instances of oldString with newString in line with the * added feature that matches of newString in oldString ignore case. * * @param line the String to search to perform replacements on * @param oldString the String that should be replaced by newString * @param newString the String that will replace all instances of oldString * * @return a String will all instances of oldString replaced by newString */ public static final String replaceIgnoreCase(String line, String oldString, String newString) { if (line == null) { return null; } String lcLine = line.toLowerCase(); String lcOldString = oldString.toLowerCase(); int i=0; if ( ( i=lcLine.indexOf( lcOldString, i ) ) >= 0 ) { char [] line2 = line.toCharArray(); char [] newString2 = newString.toCharArray(); int oLength = oldString.length(); StringBuffer buf = new StringBuffer(line2.length); buf.append(line2, 0, i).append(newString2); i += oLength; int j = i; while( ( i=lcLine.indexOf( lcOldString, i ) ) > 0 ) { buf.append(line2, j, i-j).append(newString2); i += oLength; j = i; } buf.append(line2, j, line2.length - j); return buf.toString(); } return line; }
public int compareToIgnoreCase(String str) 比较是否相等后,是0就替换
既而大小写有意义,你的不分大小写替换又有什么意义呢?
呵呵,只是问问 ------------------------------------------------------
我们还年轻牛奶会有的奶牛也会有的
可天天在 csdn 混这些会有吗 ??
1、全部转换成小写(大写),存为另一个字符串:tempStr
2、查找需要替换的位置:tempStr.indexOf()
3、替换源字符串相应的位置
/**
* Replaces all instances of oldString with newString in line with the
* added feature that matches of newString in oldString ignore case.
*
* @param line the String to search to perform replacements on
* @param oldString the String that should be replaced by newString
* @param newString the String that will replace all instances of oldString
*
* @return a String will all instances of oldString replaced by newString
*/
public static final String replaceIgnoreCase(String line, String oldString,
String newString)
{
if (line == null) {
return null;
}
String lcLine = line.toLowerCase();
String lcOldString = oldString.toLowerCase();
int i=0;
if ( ( i=lcLine.indexOf( lcOldString, i ) ) >= 0 ) {
char [] line2 = line.toCharArray();
char [] newString2 = newString.toCharArray();
int oLength = oldString.length();
StringBuffer buf = new StringBuffer(line2.length);
buf.append(line2, 0, i).append(newString2);
i += oLength;
int j = i;
while( ( i=lcLine.indexOf( lcOldString, i ) ) > 0 ) {
buf.append(line2, j, i-j).append(newString2);
i += oLength;
j = i;
}
buf.append(line2, j, line2.length - j);
return buf.toString();
}
return line;
}
比较是否相等后,是0就替换
String newString = oldString.replaceAll("(?i)abc", "ABC");
System.out.println(newString);
newString = oldString.replaceAll("a(?i)bc", "ABC");
System.out.println(newString);
newString = oldString.replaceAll("a((?i)b)c", "ABC");
System.out.println(newString); 输出:
ABCde123ABC
ABCde123Abc
abCde123Abc
不过我想不用这么难,这个问题只要大小写不敏感,p.compareToIgnoreCase(String str)
p为原串