String strToReplace="abc[todo1]dfdjf[todo4]rer";
String strReplaced = "OK";
String strResult="";
String s1="[";
String s2="]";
int index1=strToReplace("s1");
int index2=0;
while(index1!=-1)
{
   index2=strToReplace("s2",index1);
   if(index2==-1)
      break;
   strToReplace=strToReplace.substring(0,index1)+strReplace+strToReplace.substring(index2+s2.length());
 }

解决方案 »

  1.   

    String strToReplace="abc[todo1]dfdjf[todo4]rer";
    String strReplaced = "OK";
    String strResult="";for(int iPos=0;strToReplace[iPos]!='\0';iPos++)
    {
      if(strToReplace[iPos]=='[')
      {
          for(;strToReplace[iPos]!=']'&&strToReplace[iPos]!='\0';iPos++);
          strResult+="OK";
      }
      else
      {
          strResult+=strToReplase[iPos];
      }
    }
      

  2.   

    奇怪,strToReplace是字符串呀,怎么能这么用呢:strToReplace[iPos]?
      

  3.   

    刚才没有测试,这个测试过了的
    class ttt1
    {
    public static void main(String[] args) 
    {
    String strToReplace="abc[todo1]dfdjf[todo4]rer";
    String strReplaced = "OK";
    String strResult="";
    String s1="[";
    String s2="]";
    int index1=strToReplace.indexOf(s1);
    int index2=0;
    while(index1!=-1)
    {
       index2=strToReplace.indexOf(s2,index1);
       if(index2==-1)
          break;
       strToReplace=strToReplace.substring(0,index1)+strReplaced+strToReplace.substring(index2+s2.length());
     index1=strToReplace.indexOf(s1,index2);
     }
    System.out.println(strToReplace);
    }
    }
      

  4.   

    public String strReplaced(String strToReplace,String reg)
     {
       StringBuffer result=new StringBuffer("");
       char cc;
       int len=strToReplace.length();
       for(int i=0;i<len;i++)
       {
        cc=strToReplace.charAt(i);
        if(cc=='['||cc==']')
        {
          result.append(reg);
        }
        else
        {
          result.append(cc);
        }
       }
       return result.toString();
     }
      

  5.   

    我目前采用的框架,挺好!
    谢谢各位!顺便问一下:
    能否通过String 的 replaceAll(String regex, String replacement)来处理?
    关键是regex怎么写(要求不要区分大小写)? 
      

  6.   

    主要参考了 xiner 和  xiaofenguser 的思路JAVA中怎么连简单的replace(str1,str2)函数都不提供?
    只是提供了replace(char oldChar, char newChar) 
    而replaceAll(String regex,String replacement)只是在1.4版本中才得以支持? 
              
      

  7.   

    正则表达式这么写:"\\[.+\\]"如果要求[和]之间只能包括字母和数字的话: "\\[[0-9a-zA-Z]+\\]"如果你不是用Jdk1.4的话,去jakarta.apache.org下载一个ORO吧。