如何计算java字符串中的空格?

2022-09-02 00:02:15

我需要计算字符串中的空格数,但是当我运行它时,我的代码给了我一个错误的数字,这是怎么回事?

 int count=0;
    String arr[]=s.split("\t");
    OOPHelper.println("Number of spaces are: "+arr.length);
    count++;

答案 1

s.length() - s.replaceAll(" ", "").length()返回空格数。

还有更多方法。例如”

int spaceCount = 0;
for (char c : str.toCharArray()) {
    if (c == ' ') {
         spaceCount++;
    }
}

等等,等等。

在您的情况下,您尝试使用 - TAB 拆分字符串。如果您改用,您将获得正确的结果。使用可能会令人困惑,因为它匹配所有白纸 - 常规空格和TABs。\t" "\s


答案 2

这是一种不同的看待它的方式,它是一个简单的单行:

int spaces = s.replaceAll("[^ ]", "").length();

这可以通过有效地删除所有非空格,然后取剩余内容(空格)的长度来工作。

您可能希望添加空检查:

int spaces = s == null ? 0 : s.replaceAll("[^ ]", "").length();

Java 8 更新

您也可以使用直播:

long spaces = s.chars().filter(c -> c == (int)' ').count();