【问题标题】:count the occurrences of a specific character in the input [duplicate]计算输入中特定字符的出现次数[重复]
【发布时间】:2011-05-03 13:38:55
【问题描述】:

可能重复:
How do I count the number of occurrences of a char in a String?

我希望计算特定字符的出现次数,例如输入中出现的“i”。

示例,来自标准输入: Lorem ipsum dolor sit amet, consectetur adipiscing elit.

这将返回6,因为字母“i”出现了 6 次(大小写很重要)。

这可以通过使用charAt(i) 遍历字符串的循环来完成。

有没有更优雅的方法来实现这一点?

【问题讨论】:

  • 这个解决方案有什么不好的地方?

标签: java char


【解决方案1】:

这与遍历字符串基本相同,但您可以创建如下方法:

private int substrCount(string findStr, string str)
{
    lastIndex = 0;
    count = 0;
    while(lastIndex != -1){
        lastIndex = str.indexOf(findStr, lastIndex);

        if(lastIndex != -1){
            count++;
        }
    }
}

【讨论】:

  • 我觉得这样更简洁: public int countCharOccurrence(String string, char countChar){ int count = 0; for(int i =0; i
【解决方案2】:

打赌你可以遍历String.indexOf() 的结果,特别是两个输入表单,你可以告诉它开始查看最后一次匹配的位置。

【讨论】:

    猜你喜欢
    • 2020-05-24
    • 2020-06-14
    • 2011-07-08
    • 2012-05-31
    • 2017-09-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多