简体   繁体   English

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

[英]How to count white spaces in a given argument?

I find it strange why spaceCount doesn't add up when the expression is "12 + 1". 我觉得奇怪的是为什么当表达式为“12 + 1”时,spaceCount不会加起来。 I get an output 0 for spaceCount even though it should be 2. Any insight would be appreciated! 我得到了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;
}

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

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

A tokenizer is overkill (and doesn't really help you) for this problem. 对于这个问题,一个标记器是过度的(并没有真正帮助你)。 Just loop through all the characters and count the spaces: 只需遍历所有字符并计算空格:

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

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

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

Can also use: 也可以用:

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

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

This will find white spaces, including special ones. 这将找到白色空间,包括特殊空间。 You can keep the pattern so you don't need to compile it every time. 您可以保留模式,这样您就不必每次都编译它。 If just need to search for " ", a loop should do it instead. 如果只需要搜索“”,则循环应该代替。

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

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

相关问题 如何将shell参数中的引号“”传递给Java,且参数中包含空格 - How to Pass Quotes “” in a shell argument to java with argument containing white spaces 递归方法如何计算字符串中的空格? - How does recursive method to count white spaces in a string work? 如何从计数中排除空格? - How do I exclude white spaces from the count? 如何删除字符串中重复的空格并计算Java中已删除的空格数? - How to remove duplicated white spaces in a string and count the number of removed spaces in Java? 如何计算一行中作为方法参数给出的正值的数量? - How to count number of positive values, given as method argument, in one line? 如何用空格分割字符串并在结果中包含空格作为元素?多个空格分割 - How to split string with white spaces and include white spaces as elements in the result?multiple white spaces splitting 当输入以空格分隔并以字母结尾时,如何计算数字的数量? - How do you count the amount of numbers when the input is given separated by spaces, ended with a letter? 如何删除JSF输出中的空格? - How to remove white spaces in JSF output? 如何摆脱数组列表中的空格? - How to get rid of white spaces in the list of an array? 如何忽略颠覆性的白色空间? - How to ignore white-spaces in subversive?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM