如何替换指定的字符串?

mychao2002 2002-11-13 02:05:29
比如我想把“abcderab"这个字符串中的‘ab’换成‘mn'怎么做?
谢谢!!
...全文
26 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
hrlixiang 2002-11-13
  • 打赏
  • 举报
回复
public static String Replace(String p_strSource, String p_strFrom, String p_strTo){
String p_strDest = "";
//get the length of the string
int l_intFromLen = p_strFrom.length();
//the position in the string
int l_intPos;
while((l_intPos=p_strSource.indexOf(p_strFrom))!=-1){
p_strDest = p_strDest + p_strSource.substring(0,l_intPos);
p_strDest = p_strDest + p_strTo;
p_strSource = p_strSource.substring(l_intPos+l_intFromLen);
}
p_strDest = p_strDest + p_strSource;
return p_strDest;
}
hotenM 2002-11-13
  • 打赏
  • 举报
回复
大哥,注释写的很清楚了

而且现在jdk1。4已经有可以用的函数了
public String repalceAll(String regex,String replacement)
mychao2002 2002-11-13
  • 打赏
  • 举报
回复
能具体解释一下吗 , 我不太明白……谢谢!!
hotenM 2002-11-13
  • 打赏
  • 举报
回复
jdk1.4里有一个方法
replaceAll
去看看吧

下面是我写的
/**
* 字符串替换函数
* @param sAll String 原来的字符串
* @param older String 要替换掉的字符串
* @param newer String 新的字符串
* @return String 替换后的结果
*/
public synchronized static String strReplace(String sAll,String sOld, String sNew){
int iT=0;
String sF = null,sH= null;
//如果新串中包括旧串,不让替多只让替少
if(sNew.indexOf(sOld)!= -1)
return sAll;

if(sAll == null || sOld==null ||sNew==null)
return sAll;
iT = sAll.indexOf(sOld);
int i = 0;
while(iT != -1){
sF = sAll.substring(0,iT);
sH= sAll.substring(iT+sOld.length());
sAll = sF+sNew+sH;
iT = sAll.indexOf(sOld);
}
return sAll;
}

62,615

社区成员

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

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