Search code examples
for-loopcharat

How replace a phrase using charAt()?


I am having trouble with this method. It is supposed to receive a sentence (word) and replace any instance of dang with #!.

It works in some cases but when the input is "dang boom dang" the output is #! boom da#!.
Does anyone have any suggestions on how to fix this?

Here is my code so far:

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

Solution

  • In your for loop replace all references to word with 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; 
    }
    

    That way you reference the updated array when you do a replace