从字符串中删除字符

Remove char from String

我想从 String 中删除一个字母 - 但该字母只出现一次:

示例:如果我的单词是 "aaba" 并且我想删除一个 'a':

输出将是 "aba" - 仅删除第一个 'a'。 (并非所有 'a'

我想到了这个:

String word = "aaba"
String newWord = word.replace(a, "");

问题是 newWord='b' 而不是 'aba'

有人可以帮忙吗?出于某种原因,我在解决这个看似简单的问题时遇到了很多困难。解决这个问题的最佳方法是什么?

我需要创建某种 ArrayList 吗?

你需要先用indexof()方法找到第一次出现的索引,然后你可以用substring()方法找到目标字符前后的文本,最后你需要使用concat() 附加它们。

Str.replaceFirst() 也很好

public String replace(char oldChar, char newChar) 将用 newChar 替换此字符串中 所有出现的 oldChar。

您应该考虑使用 public String replaceFirst(String regex,String replacement),它将此字符串中与给定正则表达式匹配的第一个子字符串替换为给定的替换项。

String word = "aaba"
String newWord = word.replaceFirst(a, "");

字符串replaceFirst()方法

public String replaceFirst(String regex, String replacement)

参数:

参数详情如下:

regex -- the regular expression to which this string is to be matched.

replacement -- the string which would replace found expression.

代码

 public static void main(String[] args) {
        String word = "aaba";
        String newWord = word.replaceFirst("a", "");
        System.out.println(newWord);
    }

输出

aba

您可以选择使用public String replaceFirst(String regex, String replacement)

regex -- 这是要匹配此字符串的正则表达式。
replacement -- 这是要替换为每个匹配项的字符串。

因为在你的代码中,你只想替换第一次出现的重复字符,你可以像下面的代码一样用空白替换它。

String word = "aaba" 
String newWord = word.replaceFirst(a, "");