【问题标题】:Finding a char's count in a String with Replace method使用 Replace 方法在字符串中查找字符的计数
【发布时间】:2015-10-13 08:32:46
【问题描述】:
String word = "abcdefg";
int a_counter = word.length() - word.replace("a", "").length();

此代码为我提供了“单词”字符串中“a”的计数。但是有人可以解释一下它是如何工作的吗?(Java)

【问题讨论】:

  • 它给出 1 作为输出,这是正确的。那有什么问题?
  • @Rehman:“但是有人可以解释一下它是如何工作的吗?”

标签: java string replace count char


【解决方案1】:

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

word.length() - 实际长度为7 word.replace("a", "") - 从字符串abcdefg中删除a,所以长度变为6返回新的字符串对象,长度为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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

        初始字符串word中的字符数

        word.length()
        

        通过从word中删除所有出现的“a”来创建一个新字符串

        word.replace("a", "")
        

        word 中不是“a”的字符数。或者从word中删除所有“a”后剩下的内容

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

        word中'a'的个数

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

        【讨论】:

          【解决方案5】:
          word.length()
          

          返回字长(感谢 Captain Obvious)。

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

          删除所有 'a' 后返回单词的长度。 以“abcdefg”为词,得到:

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

          【讨论】:

            猜你喜欢
            • 2016-08-09
            • 2012-02-21
            • 1970-01-01
            • 2019-02-01
            • 1970-01-01
            • 2023-03-14
            • 1970-01-01
            • 1970-01-01
            • 2012-05-10
            相关资源
            最近更新 更多