如何计算给定参数中的空格?

时间:2015-02-02 22:17:36

标签: java string token tokenize

我觉得奇怪的是为什么当表达式为" 12 + 1"时,spaceCount不会加起来。我得到了spaceCount的输出0,即使它应该是2.任何见解都会受到赞赏!

public int countSpaces(String expr) {
    String tok = expr;

    int spaceCount = 0;

    String delimiters = "+-*/#! ";
    StringTokenizer st = new StringTokenizer(expr, delimiters, true);

    while (st.hasMoreTokens()) {
        if ((tok = st.nextToken()).equals(" ")) {
            spaceCount++;
        }
    }
    return spaceCount; // the expression is: 12 + 1, so this should return 2, but it returns 0;
}

5 个答案:

答案 0 :(得分:3)

您的代码似乎没问题,但如果您想计算空格,可以使用此代码:

int count = str.length() - str.replace(" ", "").length();

答案 1 :(得分:0)

对于此问题,令牌化程序是过度的(并且对您没有帮助)。只需遍历所有字符并计算空格:

public int countSpaces( String expr )
{
    int count = 0;
    for( int i = 0; i < expr.length(); ++i )
    {
        if( expr.charAt(i) == ' ' )
            ++count;
    }
    return count;
}

答案 2 :(得分:0)

另一个单行解决方案可以是以下,它也对字符串执行NULL检查。

int spacesCount = str == null ? 0 : str.length() - str.replace(" ", "").length();

答案 3 :(得分:0)

也可以使用:

String[] strArr = st.split(" ");

if (strArr.length > 1){
   int countSpaces = strArr.length - 1;
}

答案 4 :(得分:0)

这将找到空白区域,包括特殊区域。 您可以保留模式,这样您就不必每次都编译它。如果只需要搜索&#34; &#34;,循环应该改为。

Matcher spaces = Pattern.compile("\\s").matcher(argumentString); int count = 0; while (spaces.find()) { count++; }