0

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

它在某些情况下有效,但当输入为"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; 
}
4

1 回答 1

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; 
}

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

于 2014-10-17T23:38:09.637 回答