求查找字符串中的字串,并把子串替换为指定的新子串的java算法。不能用java中的所以现成的替换方法。要自己写算法实现

解决方案 »

  1.   


    public class Other {
    public static String replace(String content,String first,String second) {
    int location = -1;
    while((location = content.indexOf(first)) >= 0){
    content = content.substring(0,location) + second + content.substring(location + first.length());
    }
    return content;
    } public static void main(String args[]) {
    // 自己写的方法
    String str = "abcdefgabasdfgs";
    System.out.println(replace(str,"fg","123"));

    // 正则
    System.out.println(str.replaceAll("fg", "123"));
    }
    }
      

  2.   

    首先要匹配 之后就好办了.
    关于匹配方面的知识,可以用KMP算法或hash表
    具体记不清了 在网上搜了一个
    匹配的例子:
    public String getMaxMatch(String a,String b) {   
            StringBuffer tmp = new StringBuffer();   
            String maxString = "";   
            int max = 0;   
            int len = 0;   
            char[] aArray = a.toCharArray();   
            char[] bArray = b.toCharArray();   
            int posA = 0;   
            int posB = 0;   
            while(posA<aArray.length-max) {   
                posB = 0;   
                while(posB<(bArray.length-max)) {                                   
                     if(aArray[posA]==bArray[posB]) {   
                          len = 1;   
                          tmp = new StringBuffer();   
                          tmp.append(aArray[posA]);                                           
                          while((posA+len<aArray.length)&&(posB+len<bArray.length)&&(aArray[posA+len]==bArray[posB+len])) {   
                               tmp.append(aArray[posA+len]);   
                               len++;   
                          }   
                          if(len>max) {   
                                max = len;   
                                maxString = tmp.toString();   
                          }   
                     }   
                          posB++;   
                }   
                          posA++;   
             }           
                return maxString;                       
        }