简体   繁体   English

我应该如何计算Java中字符串开头字符出现的次数

[英]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. 有一个counter变量来计数出现的次数。 Then loop through the entire String , using charAt(i) to get the char at position i . 然后使用charAt(i)遍历整个String以获得位置i处的char Test to see if it's equal to charAt(0) . 测试一下是否等于charAt(0) If it is, increment counter and if it isn't, break out of the loop. 如果是,则增加counter ,如果不是,则break循环。

Take a look at the String javadoc . 看一下String javadoc It contains methods you can use to get the length of the String and get characters at certain positions. 它包含可用于获取String的长度并在某些位置获取字符的方法。

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: 如果您不想使用任何外部jar,只需编写一个简单的函数即可:

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: 您也可以使用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. 但是对于这种琐碎的任务,我更喜欢使用简单循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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