public static int replacer(String oldS,String newS)
{
    int num = 0;
    for(int i=0;i<oldS.length();i++) {
int check = oldS.indexOf(newS,i);
if(check != -1) {
i = check;
num ++;
}else {
break;
}
}
    return num;
}

解决方案 »

  1.   


    用JDK1.4,String自带有此替换方法,听说的
      

  2.   

    随便写了一个,作为参考:
       public static int getReplace(StringBuffer sb, String strSrc, String strDst) {
          // do some pretreatment firstly
          // i.e. when strSrc is NULL or is empty
          
          String str = sb.toString();
          StringBuffer sbReturn = new StringBuffer();
          int i, curr = 0, count = 0, len = strSrc.length();
          while ((i = str.indexOf(strSrc, curr)) != -1) {
             sbReturn.append(str.substring(curr, i));
             sbReturn.append(strDst);
             curr = i + len;
             count++;
          }
          sb.replace(0, sb.length(), sbReturn.toString());
          return count;
       }
      

  3.   

    String本来就提供这个功能啊
    class  test
    {
    public static void main(String[] args) 
    {
    String reStr = "this is a back and is all";
    System.out.println(reStr);
    reStr = reStr.replaceAll("is","as");
    System.out.println(reStr);
    }
    }然后就是求替换多少次了class  test
    {
    public static void main(String[] args) 
    {
    String reStr = "this is a back and is all";
    String re  = "is";
    String tempStr =reStr;
    int i = 0;
    int count = 0;
    do
    {
    i = tempStr.indexOf(re); if(i==-1)
    { }
    else
    {
    count++;
    tempStr = tempStr.substring(i+1);
    }
    }
    while(i!=-1);
    System.out.println(count);
    System.out.println(reStr);
    reStr = reStr.replaceAll("is","as");
    System.out.println(reStr); }
    }
      

  4.   

    实在是胡涂,这个方法应该给三个参数的,^_^,忙胡涂了.
    int 方法(全文,老字串,新字串)^_^,不好意思.
    whiteshen(White Shen)的方法 调试中.....
      

  5.   

    public static int getReplace(StringBuffer sb, String strSrc, String strDst) {
          // do some pretreatment firstly
          // i.e. when strSrc is NULL or is empty
          
          String str = sb.toString();
          StringBuffer sbReturn = new StringBuffer();
          int i, curr = 0, count = 0, len = strSrc.length();
         
          while ((i = str.indexOf(strSrc, curr)) != -1) {
          
             sbReturn.append(str.substring(curr, i));
             
             sbReturn.append(strDst);
           
             curr = i + len;
             count++;
           
          }
          sbReturn.append(str.substring(curr,str.length())); /**/
          sb.replace(0, sb.length(), sbReturn.toString());
          return count;
       }}
    好了,没问题了
    谢谢