java 的String, StringBuffer都没有提供子字符串替换函数,要实现该功能必须自己编写函数以下是两种实现方法:方法1, 使用正则替换(其实没真正用正则,函数compile的参数Pattern.LITERA使正则表达式字符串只作为字面值来对待)。
import java.util.regex.*;
public class test{
public static void main(String[] args){
String s="My name is xinyu!";
replaceFromString(s,"name","nickname");
System.out.println(s);
}
public static void replaceFromString(String string1,String string2,String string3) {
String newString = Pattern.compile(string2, Pattern.LITERAL).matcher(string1).replaceAll(string3);
System.out.println(newString);
}
}
方法2:(使用String的indexOf查找子串,然后把原串前面的内容和替换串添加到StringBuffer中,只到查找完原串)
/**
*@author Hans Bergsten, Gefion software (www.gefionsoftware.com)
*/
public class StringUtils {
/** * Returns a String with all occurrences of the String from * replaced by the String to.
* * @return The new String */
public static String replaceInString(String in, String from, String to) {
StringBuffer sb = new StringBuffer(in.length() * 2);
String posString = in.toLowerCase();
String cmpString = from.toLowerCase();
int i = 0;
boolean done = false;
while (i < in.length() && !done) {
int start = posString.indexOf(cmpString, i);
if (start == -1) {
done = true;
} else {
sb.append(in.substring(i, start) + to);
i = start + from.length();
}
}
if (i < in.length()) {
sb.append(in.substring(i));
}
return sb.toString();
}
}