【问题标题】:How replace a phrase using charAt()?如何使用 charAt() 替换短语?
【发布时间】:2014-10-17 23:06:57
【问题描述】:

我在使用这种方法时遇到了问题。它应该接收一个句子(单词)并将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; 
}

【问题讨论】:

    标签: for-loop charat


    【解决方案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-11-27
      • 2013-03-11
      • 2021-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-12
      相关资源
      最近更新 更多