gpt4 book ai didi

java - 在某个字符第一次出现时停止

转载 作者:行者123 更新时间:2023-11-30 02:21:19 26 4
gpt4 key购买 nike

我只想删除“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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com