java字符串替换算法_字符串替换算法【java】public class StringReplace {
/**
* 字符串替换
* @param srcString
* @param oldString
* @param newString
* @return
*/
public String replace(String srcString, String oldString, String newString) {
if(srcString == null) {
return null;
}
char[] lineChars = CharArray();
char[] newStringChars = CharArray();
int oldLength = oldString.length();
StringBuffer buf = new StringBuffer(lineChars.length); //⽤于存储替换后的字符串
int i = 0;
int j = i;
while((i = srcString.indexOf(oldString,i)) >= 0){
buf.append(lineChars, j, i-j).append(newStringChars);
i += oldLength;
j = i;
}
buf.append(lineChars, j, lineChars.length - j); //拼接源字符串后⾯剩下的字符串
String();
}
public static void main(String[] args) {
StringReplace mp = new StringReplace();
String str = "xbn_sxsghdhs我是中国⼈xxshjsh中国s_sx我爱中国;;;XH_sx()8jsdh*^_sxghdgshd";
long start = System.nanoTime();
System.out.place(str, "_sx", "$$$"));
System.out.println(System.nanoTime() - start);
String str1 = "xbn_sxsghdhs我是中国⼈xxshjsh中国s_sx我爱中国;;;XH_sx()8jsdh*^_sxghdgshd";
java replace方法start = System.nanoTime();
System.out.place("_sx", "$$$"));
System.out.println(System.nanoTime() - start);
String str2 = "%gsfg^gsgh*jChinanxj&^&bbsnakkIloveChina*#KChina#@wdschiaChina"; start = System.nanoTime();
System.out.place(str2, "China", "中国"));
System.out.println(System.nanoTime() - start);
start = System.nanoTime();
System.out.place("China", "中国"));
System.out.println(System.nanoTime() - start);
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。