开发者

How should I count the number of occurrences of a character at the beginning of a string in Java

I have a string similar to this ,,,foo开发者_运维知识库,bar and I need to count the amount of "," at the beginning of the string in java any ideas?


Have a counter variable which counts the number of occurrences. Then loop through the entire String, using charAt(i) to get the char at position i. Test to see if it's equal to charAt(0). If it is, increment counter and if it isn't, break out of the loop.


Take a look at the String javadoc. It contains methods you can use to get the length of the String and get characters at certain positions.


If starting characters are known then build a regex pattern and get the first group. First group string will contain the exact match of desired sequence, length of this string is the resultant count.


You can also use regexp:

public static int countCommasAtBegin(String str) {
    Matcher commas = Pattern.compile("^,*").matcher(str);
    if (commas.find()) {
        return commas.group().length();
    } else {
        return 0;
    }
}

but for such trivial task I prefer to use simple loop.


A simple loop (while or for) containing a if with a condition of equality that increments a counter if true should be enough.


This quick-n-dirty solution worked for me.

public static void main(String[] args)
{
    String s = ",,,foo,bar";
    int count = 0;
    for (int i = 0; i < s.length() ; i++) {
        if (s.charAt(i) != ',')
            break;
        count++;
    }

    System.out.println("count " + count);
}

Update: just realized that you only need to count the ',' at the beginning of the string and not the middle. I've updated the code to do that.


If you don't want to use any any external jars just write a simple function:

public static int countAtBegin(String str, char c) {
    for (int ret = 0; ret < str.length(); ret++) {
        if (str.charAt(ret) != c)
            return ret;
    }
    return str.length();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜