java 的String, StringBuffer都沒有提供子字串替換函數,要實現該功能必須自己編寫函數以下是兩種實現方法:方法1, 使用正則替換(其實沒真正用正則,函數compile的參數Pattern.LITERA使Regex字串只作為字面值來對待)。
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();
}
}