JAVA字符串替换

kjeny2002 2003-12-18 02:27:42
我整理了一下,有几个是网友写的,jdk1.4以上应是自带的吧


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;
}
...全文
2372 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

23,407

社区成员

发帖
与我相关
我的任务
社区描述
Java 非技术区
社区管理员
  • 非技术区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧