如何计算字符串中char的出现次数? [英] How do I count the number of occurrences of a char in a String?

查看:88
本文介绍了如何计算字符串中char的出现次数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有字符串

a.b.c.d

我想以惯用的方式计算'。'的出现次数,最好是单行。

I want to count the occurrences of '.' in an idiomatic way, preferably a one-liner.

(之前我已经把这个约束表达为没有循环,如果你想知道为什么每个人都试图回答而不使用循环)。

(Previously I had expressed this constraint as "without a loop", in case you're wondering why everyone's trying to answer without using a loop).

推荐答案

这个怎么样?它不使用下面的regexp,所以应该比其他一些解决方案更快,并且不会使用循环。

How about this. It doesn't use regexp underneath so should be faster than some of the other solutions and won't use a loop.

int count = line.length() - line.replace(".", "").length();

这篇关于如何计算字符串中char的出现次数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆