使用 Replace 方法查找字符串中字符的计数

Finding a char's count in a String with Replace method

String word = "abcdefg";
int a_counter = word.length() - word.replace("a", "").length();

此代码给出 'word' 字符串中 'a' 的计数。但是有人可以解释一下它是如何工作的吗?(Java)

添加syso语句后现在应该清楚了。

word.length() - 实际长度为 7 word.replace("a", "") - 从字符串 abcdefg 中删除 a,因此长度变为 6return 新长度为 6

的字符串对象
public static void main(String[] args) throws Exception {
        String word = "abcdefg";
        System.out.println(word.length());
        System.out.println(word.replace("a", "").length());
        int a_counter = word.length() - word.replace("a", "").length();
        System.out.println(a_counter);
    }

输出

7
6
1

word.length() 给出字符串中所有字符的数量。 word.replace("a", "") 从初始字符串中删除所有 'a' 并生成一个新字符串。两者的长度之差就是初始字符串中“a”的数量...

word.length() = 7 和 word.replace("a", "") = bcdefg 其长度为 6 所以 7-6 =1

初始String中的字符数word

word.length()

通过从 word

中删除所有出现的 'a' 创建一个新字符串
word.replace("a", "")

word 中不属于 'a' 的字符数。或者从 word

中删除所有 'a' 后剩下的东西
word.replace("a", "").length()

word

中'a'的人数
word.length() - word.replace("a", "").length();
word.length()

Returns 字长(感谢 Captain Obvious)。

word.replace("a", "").length

Returns全部删除后的单词长度'a'。 使用 "abcdefg" 作为单词,您将得到:

"abcdefg".length - "bcdefg".length
= 7 - 6
= 1