如何使用charAt()替换短语?

时间:2014-10-17 23:06:57

标签: for-loop charat

我遇到了这种方法的问题。它应该接收一个句子(单词)并用dang替换#!的任何实例。

在某些情况下有效但输入为"dang boom dang"时输出为#! boom da#! 有没有人对如何解决这个问题有任何建议?

到目前为止,这是我的代码:

public static String deleteDang(String word) 
{ 
    StringBuffer wordSB = new StringBuffer(word); 
    int length = wordSB.length(); 
    for (int i = 0; i < length; i++) 
    { 
        if (word.charAt(i)=='d'|| word.charAt(i)=='D') 
            if (word.charAt(i+1)=='a'|| word.charAt(i+1)=='A') 
                if (word.charAt(i+2)=='n'|| word.charAt(i+2)=='N') 
                    if (word.charAt(i+3)=='g'|| word.charAt(i+3)=='G') 
                        wordSB = wordSB.replace(i,i+4, "#!"); 
        length = wordSB.length(); 
    } 
    String newWord = wordSB.toString(); 
    return newWord; 
}

1 个答案:

答案 0 :(得分:1)

在for循环中,用wordSB替换所有对word的引用

public static String deleteDang(String word) 
{ 
      StringBuffer wordSB = new StringBuffer(word); 
      int length=wordSB.length(); 
      for (int i=0; i<length; i++) 
      { 
           if (wordSB.charAt(i)=='d'|| wordSB.charAt(i)=='D') 
           if (wordSB.charAt(i+1)=='a'|| wordSB.charAt(i+1)=='A') 
           if (wordSB.charAt(i+2)=='n'|| wordSB.charAt(i+2)=='N') 
           if (wordSB.charAt(i+3)=='g'|| wordSB.charAt(i+3)=='G') 
           wordSB = wordSB.replace(i,i+4, "#!"); 
           length=wordSB.length(); 
      } 

      String newWord= wordSB.toString(); 
      return newWord; 
}

这样,您在执行替换时引用更新的数组