自己写的字符替换类

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

23,404

社区成员

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

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