我只想删除“brealdeke”中的“a” 这个程序有效,它打印“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"));
}
}
最佳答案
你可以尝试:
"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"));
}
关于java - 在某个字符第一次出现时停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46739270/