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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9655753/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 05:42:13  来源:igfitidea点击:

how to count the spaces in a java string?

javastring

提问by kamweshi

I need to count the number of spaces in my string but my code gives me a wrong number when i run it, what is wrong?

我需要计算字符串中的空格数,但是我的代码在运行时给出了错误的数字,有什么问题?

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

回答by nikhil500

Your code will count the number of tabs and not the number of spaces. Also, the number of tabs will be one less than arr.length.

您的代码将计算制表符的数量而不是空格的数量。此外,选项卡的数量将比 少 1 arr.length

回答by Kurt Kaylor

The code you provided would print the number of tabs, not the number of spaces. The below function should count the number of whitespace characters in a given string.

您提供的代码将打印制表符的数量,而不是空格的数量。下面的函数应该计算给定字符串中的空白字符数。

int countSpaces(String string) {
    int spaces = 0;
    for(int i = 0; i < string.length(); i++) {
        spaces += (Character.isWhitespace(string.charAt(i))) ? 1 : 0;
    }
    return spaces;
}

回答by chooban

\twill match tabs, rather than spaces and should also be referred to with a double slash: \\t. You could call s.split( " " )but that wouldn't count consecutive spaces. By that I mean...

\t将匹配制表符,而不是空格,也应该用双斜线表示:\\t。你可以打电话,s.split( " " )但这不会计算连续的空格。我的意思是...

String bar = " ba jfjf jjj j   ";
String[] split = bar.split( " " );
System.out.println( split.length ); // Returns 5

So, despite the fact there are seven space characters, there are only five blocks of space. It depends which you're trying to count, I guess.

因此,尽管有七个空格字符,但只有五个空格。我猜这取决于你要数哪个。

Commons Langis your friend for this one.

Commons Lang是你的朋友。

int count = StringUtils.countMatches( inputString, " " );

回答by AlexR

s.length() - s.replaceAll(" ", "").length()returns you number of spaces.

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

There are more ways. For example"

还有更多的方法。例如”

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

etc., etc.

等等等等。

In your case you tried to split string using \t- TAB. You will get right result if you use " "instead. Using \smay be confusing since it matches all whitepsaces- regular spaces and TABs.

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

回答by Bohemian

Here's a different way of looking at it, and it's a simple one-liner:

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

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

This works by effectively removing all non-spaces then taking the length of what's left (the spaces).

这通过有效地删除所有非空格然后取剩下的长度(空格)来工作。

You might want to add a null check:

您可能想要添加一个空检查:

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


Java 8 update

Java 8 更新

You can use a stream too:

您也可以使用流:

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

回答by Peter Lawrey

Another way using regular expressions

使用正则表达式的另一种方式

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

回答by Adam

A solution using java.util.regex.Pattern / java.util.regex.Matcher

使用 java.util.regex.Pattern / java.util.regex.Matcher 的解决方案

String test = "foo bar baz ";
Pattern pattern = Pattern.compile(" ");
Matcher matcher = pattern.matcher(test);
int count = 0;
while (matcher.find()) {
    count++;
}
System.out.println(count);

回答by Konstantin Pribluda

Fastest way to do this would be:

最快的方法是:

int count = 0;
for(int i = 0; i < str.length(); i++) {
     if(Character.isWhitespace(str.charAt(i))) count++;
}

This would catch all characters that are considered whitespace.

这将捕获所有被视为空白的字符。

Regex solutions require compiling regex and excecuting it - with a lot of overhead. Getting character array requires allocation. Iterating over byte array would be faster, but only if you are sure that your characters are ASCII.

正则表达式解决方案需要编译正则表达式并执行它 - 有很多开销。获取字符数组需要分配。迭代字节数组会更快,但前提是您确定您的字符是 ASCII。

回答by S N Prasad Rao

please check the following code, it can help

请检查以下代码,它可以帮助

 public class CountSpace {

    public static void main(String[] args) {

        String word = "S N PRASAD RAO";
        String data[];int k=0;
        data=word.split("");
        for(int i=0;i<data.length;i++){
            if(data[i].equals(" ")){
                k++;
            }

        }
        System.out.println(k);

    }
}

回答by James Drinkard

I just had to do something similar to this and this is what I used:

我只需要做类似的事情,这就是我使用的:

String string = stringValue;
String[] stringArray = string.split("\s+");
int length = stringArray.length;
System.out.println("The number of parts is: " + length);