在第一次出现角色时停止

时间:2017-10-13 23:28:39

标签: java charat

我只想删除' a' in" brealdeke" 这个程序有效,它打印" breldeke"但如果我要放 " brealdeake"用2' a'在这个字符串中,它变得狂暴和打印:breldeakebrealdeke如何解决它?谢谢 我真的希望看到这个:

class Example {
    public static String suppression(char c, String s) {
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == c) {
                int position = i;
                for (int a = 0; a < position; a++) {
                    System.out.print(s.charAt(a));
                }
                for (int b = position + 1; b < s.length(); b++) {
                    System.out.print(s.charAt(b));
                }
            }

        }
        return "";
    }

    public static void main(String[] args) {
        // prints "breldeke"
        System.out.println(suppression('a', "brealdeke"));
        // prints "breldeakebrealdeke"
        System.out.print(suppression('a', "brealdeake"));
    }
}

2 个答案:

答案 0 :(得分:2)

你可以尝试:

"banana".replaceFirst("a", "");

这会返回bnana

编辑:希望这不包括你还没有学过的任何东西

public static void main(String[] args) {
    String word = "banana";
    String strippedWord = "";
    boolean found = false;
    for (int i = 0; i < word.length(); i++) {
        if (word.charAt(i) == 'a' && !found) found = !found;
        else strippedWord += word.charAt(i);
    }
    System.out.println(strippedWord);
}

这会打印bnana

EDIT2 :你说你想在一个函数中使用它,同样适用:

public static String suppression(char c, String word) {
    String strippedWord = "";
    boolean charRemoved = false;    // This is a boolean variable used to know when the char was skipped!
    for (int i = 0; i < word.length(); i++) {
        // If the current letter is for example 'a' and we haven't yet skipped the char, skip this char we're at 
        if (word.charAt(i) == c && charRemoved == false) charRemoved = true;
        else strippedWord += word.charAt(i);
    }
    return strippedWord;
}

public static void main(String[] args) {
    // prints "breldeke"
    System.out.println(suppression('a', "brealdeke"));
    // prints "breldeake"
    System.out.print(suppression('a', "brealdeake"));
}

答案 1 :(得分:0)

其他变量好吗?

我个人这样做:

public static String removeFirstLetter(string s, char c)
{
   String word = "";
   Bool foundChar = false;

   for ( int i = 0; i<s.length();i++) {
      if (s.charAt(i).toLower() != c)
      {
         word += s.char(i);
      }
    else
    {
       if (foundChar == false){
           foundChar = true;
       }  
       else
       {
           word += s.char(i);
       }
     }
   }
}

 System.out.print(word);