老师布置的一个作业~~ 有兴趣的做下
   自己写方法实现replace的功能~
  本来以为很简单 偶用String 截出前半部分和后半部分然后连接起来 ~但做起来真的很麻烦~
  ---没办法了  看看这边有没高手 帮帮忙~  谢 啊 ~~

解决方案 »

  1.   

    这是Java中replace的源代码: public String replace(char oldChar, char newChar) {
    if (oldChar != newChar) {
        int len = count;
        int i = -1;
        char[] val = value; /* avoid getfield opcode */
        int off = offset;   /* avoid getfield opcode */     while (++i < len) {
    if (val[off + i] == oldChar) {
        break;
    }
        }
        if (i < len) {
    char buf[] = new char[len];
    for (int j = 0 ; j < i ; j++) {
        buf[j] = val[off+j];
    }
    while (i < len) {
        char c = val[off + i];
        buf[i] = (c == oldChar) ? newChar : c;
        i++;
    }
    return new String(0, len, buf);
        }
    }
    return this;
        }参考一下~~
      

  2.   

    有点看不懂~count 和 value 是变量?
    还有 是写 public String replace(String oldC, String newC) 参数是两个String类的 那个方法 
      

  3.   

    String 中的那个方法:public String replace(String oldC, String newC)根本不是普通的能看懂的,是采用正则表达式的字面模式实现的。
    要看懂这个得先看懂 Pattern 和 Matcher 两个类的的五六千代码。
      

  4.   

    public class toString {

    public static String replaceStr(String str, String problemStr, String replace){     for(int i=str.lastIndexOf(problemStr); i>=0; i=str.lastIndexOf(problemStr, i-1)){         if(i==0){             str = replace+str.substring(i+1, str.length());         }         else{             str = str.substring(0, i)+replace+str.substring(i+1, str.length());         }//end if     }//end for     return str; }
    }
      

  5.   

    public class Test {    public static void main(String[] args) {
            String str = "123aa123aaa123bbb123ccc123ddd123aa123";
            System.out.println(str);
            System.out.println(replace(str, "123", "***"));
        }
        
        public static String replace(String str, String old, String replacement) {
            StringBuffer sb = new StringBuffer();
            int index = str.indexOf(old);
            if(index < 0) {
                return str;
            }
            int start = 0;
            int len = old.length();
            do {
                sb.append(str.substring(start, index))
                  .append(replacement);
                start = index + len;
                index = str.indexOf(old, start);
            } while (index >= 0);
            sb.append(str.substring(start));
            return sb.toString();
        }
    }
      

  6.   

    呵呵 多谢大家了 ~ 今下午偶也研究出来了~~ 代码也蛮简单~public class Test {    public static void main(String[] args) {
            String str = "123aa123aaa123bbb123ccc123ddd123aa123";
        String old = "123", snew = "***";
    String fw = "";
    int index = -1;
    while((index=str.indexOf(old))!= -1){
      fw += str.substring(0,index) + snew ;
      str = str.substring(index +old.length(),str.length());  } String res = fw+str; System.out.println(str);        System.out.println(res);        
        }
    }