计算字符串中字符出现次数的简单方法

问题描述:

是否有一种简单的方法(而不是手动遍历所有字符串,或循环遍历indexOf)以便查找字符出现在字符串中的次数?

Is there a simple way (instead of traversing manually all the string, or loop for indexOf) in order to find how many times, a character appears in a string?

假设我们有abdsd3 $ asda $ asasdd $ sadas,我们希望$出现3次。

Say we have "abdsd3$asda$asasdd$sadas" and we want that $ appears 3 times.

String s = "...";
int counter = 0;
for( int i=0; i<s.length(); i++ ) {
    if( s.charAt(i) == '$' ) {
        counter++;
    } 
}

这绝对是最快的方法。这里的正则表达式要慢得多,而且可能更难理解。

This is definitely the fastest way. Regexes are much much slower here, and possible harder to understand.