Java 查找字符';s使用Replace方法在字符串中计数

Java 查找字符';s使用Replace方法在字符串中计数,java,string,replace,count,char,Java,String,Replace,Count,Char,这段代码给出了“word”字符串中“a”的计数。但是有人可以向我解释它是如何工作的?(Java)在添加了syso语句之后,现在应该很清楚了 word.length()-实际长度,即7 word.replace(“a”,”)-从字符串abcdefg中删除a,使长度变为6,返回长度6的新字符串对象 String word = "abcdefg"; int a_counter = word.length() - word.replace("a", "").length(); 输出 public st

这段代码给出了“word”字符串中“a”的计数。但是有人可以向我解释它是如何工作的?(Java)

在添加了
syso
语句之后,现在应该很清楚了

word.length()
-实际长度,即
7
word.replace(“a”,”)-从字符串
abcdefg
中删除
a
,使长度变为
6
返回长度
6
的新字符串对象

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

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);
    }
word.length()
提供字符串中所有字符的数目。
word.replace(“a”,”)
从初始字符串中删除所有“a”,并生成新字符串。两者的长度之差就是初始字符串中“a”的数量…

word.length()
=7和
word.replace(“a”,即“)
=bcdefg,其长度为6,因此7-6=1

初始字符串中的字符数
word

7
6
1
word.length()
word.replace("a", "")
word.replace("a", "").length()
通过从
word

7
6
1
word.length()
word.replace("a", "")
word.replace("a", "").length()

单词中非“a”的字符数。或者从
word

7
6
1
word.length()
word.replace("a", "")
word.replace("a", "").length()
word

7
6
1
word.length()
word.replace("a", "")
word.replace("a", "").length()
返回单词长度(谢谢)

返回删除所有“a”后的单词长度。 使用“abcdefg”作为单词,您可以得到:

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

它的输出为1,这是正确的。“这有什么不对吗?”雷曼:“但有人能告诉我它是如何工作的?”