How do I count the number of occurrences of a char

2018-12-31 01:46发布

I have the string

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).

标签: java string
30条回答
骚的不知所云
2楼-- · 2018-12-31 02:44
public static int countOccurrences(String container, String content){
    int lastIndex, currIndex = 0, occurrences = 0;
    while(true) {
        lastIndex = container.indexOf(content, currIndex);
        if(lastIndex == -1) {
            break;
        }
        currIndex = lastIndex + content.length();
        occurrences++;
    }
    return occurrences;
}
查看更多
临风纵饮
3楼-- · 2018-12-31 02:44

Using Eclipse Collections

int count = CharAdapter.adapt("a.b.c.d").count(c -> c == '.');

If you have more than one character to count, you can use a CharBag as follows:

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

Note: I am a committer for Eclipse Collections.

查看更多
初与友歌
4楼-- · 2018-12-31 02:45

The simplest way to get the answer is as follow:

public static void main(String[] args) {
    String string = "a.b.c.d";
    String []splitArray = string.split("\\.");
    System.out.println("No of . chars is : " + splitArray.length-1);
}
查看更多
美炸的是我
5楼-- · 2018-12-31 02:45

Why not just split on the character and then get the length of the resulting array. array length will always be number of instances + 1. Right?

查看更多
临风纵饮
6楼-- · 2018-12-31 02:46
String s = "a.b.c.d";
long result = s.chars().filter(ch -> ch == '.').count();
查看更多
无色无味的生活
7楼-- · 2018-12-31 02:47

My 'idiomatic one-liner' for this is:

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

Why write it yourself when it's already in commons lang?

Spring Framework's oneliner for this is:

int occurance = StringUtils.countOccurrencesOf("a.b.c.d", ".");
查看更多
登录 后发表回答