最近在網上搜集了一些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 閱讀(38999)
評論(4) 編輯 收藏 所屬分類:
Jsp