我有字符串

a.b.c.d

我想数一下'的出现次数。,最好是一句单句俏皮话。

(之前我把这个约束表述为“不使用循环”,以防你想知道为什么每个人都试图在不使用循环的情况下回答)。


当前回答

使用lambda函数删除所有字符进行计数 计数是前长度和后长度之差

String s = "a.b.c.d";
int count = s.length() - deleteChars.apply( s, "." ).length();  // 3

在这里找到deleteChars

如果你需要计算多个字符的出现次数,你可以一次性完成: 如。对于b c和。

int count = s.length() - deleteChars.apply( s, "bc." ).length();  // 5

其他回答

这就是我用来计算字符串出现次数的方法。

希望有人觉得有用。

    private long countOccurrences(String occurrences, char findChar){
        return  occurrences.chars().filter( x -> {
            return x == findChar;
        }).count();
    }

我有一个类似于Mladen的想法,但恰恰相反……

String s = "a.b.c.d";
int charCount = s.replaceAll("[^.]", "").length();
println(charCount);

使用Java 8和HashMap,没有任何库来计数所有不同的字符:

private static void countChars(String string) {
    HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
    string.chars().forEach(letter -> hm.put(letter, (hm.containsKey(letter) ? hm.get(letter) : 0) + 1));
    hm.forEach((c, i) -> System.out.println(((char)c.intValue()) + ":" + i));
}

我对此的“惯用语”是:

int count = StringUtils.countMatches("a.b.c.d", ".");

既然已经是通用语言了,为什么还要自己写呢?

Spring Framework的线性程序是:

int occurance = StringUtils.countOccurrencesOf("a.b.c.d", ".");

我的“惯用的一句话”解决方案:

int count = "a.b.c.d".length() - "a.b.c.d".replace(".", "").length();

不知道为什么使用StringUtils的解决方案是可以接受的。