【问题标题】:How to count white spaces in a given argument?如何计算给定参数中的空格?
【发布时间】:2015-02-02 22:17:35
【问题描述】:

我觉得很奇怪为什么当表达式为“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;
}

【问题讨论】:

标签: java string token tokenize


【解决方案1】:

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

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

【讨论】:

  • 简单有效的代码。只是不要忘记在这里检查空条件。
  • 在将这种方法用于带有“大量”空格的“大”字符串之前,我只是确保我了解replace 的时间复杂度。这可能效率很低。
【解决方案2】:

对于这个问题,分词器是矫枉过正(并不能真正帮助你)。只需遍历所有字符并计算空格:

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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      【解决方案4】:

      也可以使用:

      String[] strArr = st.split(" ");
      
      if (strArr.length > 1){
         int countSpaces = strArr.length - 1;
      }
      

      【讨论】:

        【解决方案5】:

        这将找到空格,包括特殊空格。 您可以保留该模式,这样您就不需要每次都编译它。如果只需要搜索“”,则应该使用循环来代替。

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-03-24
          • 2018-09-19
          • 2018-06-19
          • 1970-01-01
          • 1970-01-01
          • 2017-02-09
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多