【问题标题】:How to check how much char space in 1 string如何检查1个字符串中有多少字符空间
【发布时间】:2017-11-15 19:09:38
【问题描述】:

假设我有一个带有一些文本的字符串:

String str="Hello My Name Is Help!"

我想检查以下String str 中有多少空格字符。我想要一个方法,该方法采用以下字符串并返回该字符串中whitespaces 的数量。例如,如果我将我的方法命名为 getNumberOfWhiteSpaces(String str) 并将其命名为 a,我应该取回空格的数量。

if( getNumberOfWhiteSpaces(String str) > 3)
     System.out.println("There are more then 3 spaces in this string");

public int getNumberOfWhiteSpaces(String str) {
  ....
  return some number
}

【问题讨论】:

标签: java string char


【解决方案1】:

一种解决方案是使用replaceAll 将所有非空格([^\s])替换为空并检查结果输出的长度:

if (str.replaceAll("[^\\s]", "").length() > 3) {...}

【讨论】:

    【解决方案2】:

    试试:

    String str="Hello My Name Is Help!";
    int spaces = str.length() - str.replace(" ", "").length();
    if(spaces > 3){
        System.out.println("There are more then 3 spaces in this string");
    }
    

    【讨论】:

      【解决方案3】:

      Java 8 方式可能是:

      s.chars().filter(Character::isWhitespace).count()
      

      这将为您提供字符串s空格 的数量。你也可以使用isSpaceChar

      【讨论】:

        猜你喜欢
        • 2022-07-13
        • 2012-01-11
        • 2011-10-13
        • 2014-06-23
        • 2017-12-31
        • 2019-08-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多