当前位置: 代码迷 >> Java相关 >> 看看错出在哪里
  详细解决方案

看看错出在哪里

热度:107   发布时间:2009-10-28 07:56:41.0
看看错出在哪里
我要替换str里的str2,换成str3里的词, 为什么我的程序会瘫痪呢?

   public String replaceSubstring()
    {
        StringBuilder str=new StringBuilder(line);
        String str2="the";
        String str3="that";
        int position;
        
        position = str.indexOf(str2);
        str.replace(position,position+str2.length(), str3);
        while (position !=-1)
        {
            position = str.indexOf(str2, position+1);
            str.replace(position,position+str2.length(), str3);
        }
            
        return str.toString();
    }

----------------解决方案--------------------------------------------------------
        
程序代码:
        String str="the aaga asgagathe";
                 
        String str2="the";
        String str3="that";

        str=str.replace(str2, str3);
         
        System.out.println(str);

----------------解决方案--------------------------------------------------------
以下是引用jedypjd在2009-10-28 09:51:08的发言:

                String str="the aaga asgagathe";
                 
        String str2="the";
        String str3="that";

        str=str.replace(str2, str3);
         
        System.out.printl ...
这种方法是很简单,但是要求是不可以用这个方法, 需要用我的方法,大家帮我改一下我的程序
----------------解决方案--------------------------------------------------------
//自己去总结吧。
import java.lang.StringBuilder;
class replace1{
    public String replaceSubstring()
      {
            StringBuilder str=new StringBuilder("cat is cat");
            String str2="cat";
            String str3="dog";
            int position;
            
            position = str.indexOf(str2);
      
          str.replace(position,position+str2.length(), str3);

            while (position !=-1)
            {
                 
                position = str.indexOf(str2, position+1);
                if(position==-1){
                    break;
                }else{
                    str.replace(position,position+str2.length(), str3);
                }
               
            }
                return str.toString();

        }
}
public class Dancitihuan {

    public static void main(String[] args) {
        replace1  re=new replace1();
        System.out.println(re.replaceSubstring());
      
    }

}

----------------解决方案--------------------------------------------------------
楼主,你是要转换“the”单词还是字符,如果是前者就要用正则表达式“\\bthe\\b”,因为很多英文单词里都包含"the"字符串, 如"weather"
----------------解决方案--------------------------------------------------------
  相关解决方案