我有字符串

a.b.c.d

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

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


当前回答

我对此的“惯用语”是:

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

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

Spring Framework的线性程序是:

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

其他回答

使用Eclipse集合

int count = Strings.asChars("a.b.c.d").count(c -> c == '.');

如果你有一个以上的字符计数,你可以使用CharBag如下所示:

CharBag bag = Strings.asChars("a.b.c.d").toBag();
int count = bag.occurrencesOf('.');

注意:我是Eclipse Collections的提交者。

下面是一个没有循环的解决方案:

public static int countOccurrences(String haystack, char needle, int i){
    return ((i=haystack.indexOf(needle, i)) == -1)?0:1+countOccurrences(haystack, needle, i+1);}


System.out.println("num of dots is "+countOccurrences("a.b.c.d",'.',0));

嗯,有一个循环,但它是看不见的:-)

——约拿单

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

希望有人觉得有用。

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

虽然方法可以隐藏它,但没有循环(或递归)就无法计数。但出于性能考虑,您希望使用char[]。

public static int count( final String s, final char c ) {
  final char[] chars = s.toCharArray();
  int count = 0;
  for(int i=0; i<chars.length; i++) {
    if (chars[i] == c) {
      count++;
    }
  }
  return count;
}

使用replaceAll(即RE)听起来不是最好的方法。

使用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