自己写的字符替换类
package test;
public class StringReplace {
/**
* 字符串替换函数(全不替换)
* @param from 要替换的字符
* @param to 要替换成的目标字符
* @param source 要替换的字符串
* @return 替换后的字符串
*/
public static String replaceAll(String strSource, String strFrom, String strTo){
if (strSource == null) {
return null;
}
if(strFrom==null || strFrom.length()<1 || strTo==null){
return strSource;
}
int i = 0;
if ((i = strSource.indexOf(strFrom, i)) >= 0) {
char[] cSrc = strSource.toCharArray();
char[] cTo = strTo.toCharArray();
int len = strFrom.length();
StringBuffer buf = new StringBuffer(cSrc.length);
buf.append(cSrc, 0, i).append(cTo);
i += len;
int j = i;
while ((i = strSource.indexOf(strFrom, i)) > 0) {
buf.append(cSrc, j, i - j).append(cTo);
i += len;
j = i;
}
buf.append(cSrc, j, cSrc.length - j);//未字符串
return buf.toString();
}
return strSource;
}
/**
* 字符串替换函数(只替换第一个)
* @param from 要替换的字符
* @param to 要替换成的目标字符
* @param source 要替换的字符串
* @return 替换后的字符串
*/
public static String replace(String strSource, String strFrom, String strTo){
if (strSource == null) {
return null;
}
if(strFrom==null || strFrom.length()<1 || strTo==null){
return strSource;
}
int i = 0;
if ((i = strSource.indexOf(strFrom, i)) >= 0) {
StringBuffer buf = new StringBuffer(strSource.length());
int len = strFrom.length();
buf.append(strSource.substring(0,i)).append(strTo).append(strSource.substring(i+len));
return buf.toString();
}
return strSource;
}
}