Java 版 (精华区)


 Q: 如何实现字符串的替换?

 [注]自jdk1.4起,提供了此方法replaceAll(str1,str2),使用正则表达式实现

 A:

  [方法1]
  public static String replace(String allstr,
                    String replstr1,String replstr2){
      while(allstr.indexOf(replstr1)!=-1)
          allstr=allstr.substring(0,allstr.indexOf(replstr1))+replstr2+
               allstr.substring(allstr.indexOf(replstr1)+replstr1.length());
      return allstr;
  }
  方法1的bug:replace("abcdefg","c","cc")   死循环,:)

  [方法2]
public static final String replace( String line, String oldString,
String newString )
    {
        int i=0;
        if ( ( i=line.indexOf( oldString, i ) ) >= 0 ) {
            char [] line2 = line.toCharArray();
            char [] newString2 = newString.toCharArray();
            int oLength = oldString.length();
            StringBuffer buf = new StringBuffer(line2.length);
            buf.append(line2, 0, i).append(newString2);
            i += oLength;
            int j = i;
            while( ( i=line.indexOf( oldString, i ) ) > 0 ) {
                buf.append(line2, j, i-j).append(newString2);
                i += oLength;
                j = i;
            }
            buf.append(line2, j, line2.length - j);
            return buf.toString();
        }
        return line;
    }
[百宝箱] [返回首页] [上级目录] [根目录] [返回顶部] [刷新] [返回]
Powered by KBS BBS 2.0 (http://dev.kcn.cn)
页面执行时间:3.392毫秒