简体   繁体   中英

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

我有一个类似于此的字符串,,,foo,bar ,我需要计算java中字符串开头的“,”数量吗?

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.

一个简单的循环(while或for),包含一个if,条件为相等,如果为true,则增加一个计数器。

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();
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM