最近在网上搜集了一些java中字符串替换的方法。
1. /**
* 字符串替换函数
* @param from 要替换的字符
* @param to 要替换成的目标字符
* @param source 要替换的字符串
* @return 替换后的字符串
*/
import java.util.StringTokenizer;
public String str_replace(String from,String to,String source) {
StringBuffer bf= new StringBuffer("");
StringTokenizer st = new StringTokenizer(source,from,true);
while (st.hasMoreTokens()) {
String tmp = st.nextToken();
if(tmp.equals(from)) {
bf.append(to);
} else {
bf.append(tmp);
}
}
return bf.toString();
}
2. /*
*字符串替换函数,另一种方法的实现
*/
public String str_replace2(String con ,String tag,String rep){
int j=0;
int i=0;
int k=0;
String RETU="";
String temp =con;
int tagc =tag.length();
while(i<con.length()){
if(con.substring(i).startsWith(tag)){
temp =con.substring(j,i)+rep;
RETU+= temp;
i+=tagc;
j=i;
}else{
i+=1;
}
}
RETU +=con.substring(j);
return RETU;
}
3.
public static String replace(String strSource, String strFrom, String strTo) {
if(strFrom == null || strFrom.equals(""))
return strSource;
String strDest = "";
int intFromLen = strFrom.length();
int intPos;
while((intPos = strSource.indexOf(strFrom)) != -1) {
strDest = strDest + strSource.substring(0,intPos);
strDest = strDest + strTo;
strSource = strSource.substring(intPos + intFromLen);
}
strDest = strDest + strSource;
return strDest;
}
4.高效替换程序。
public static String replace(String strSource, String strFrom, String strTo) {
if (strSource == null) {
return null;
}
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;
}
posted on 2006-06-08 09:06
fish的Blog 阅读(38991)
评论(4) 编辑 收藏 所属分类:
Jsp