2014-10-17 58 views
0

我遇到了這種方法的麻煩。它應該收到一個句子(單詞)並用#!替換dang的任何實例。如何用charAt()替換一個短語?

它在某些情況下有效,但是當輸入爲"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

在你的for循環與wordSB

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

替換字的所有引用當你做一個替換

您引用更新數組的方式