简体   繁体   English

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

[英]how to count the spaces in a java string?

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++;

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. 在您的情况下,您尝试使用\\t - TAB拆分字符串。 You will get right result if you use " " instead. 如果您使用" "您将获得正确的结果。 Using \\s may be confusing since it matches all whitepsaces - regular spaces and TABs. 使用\\s可能会造成混淆,因为它匹配所有whitepsaces - 常规空格和TAB。

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();

If you use Java 8, the following should work: 如果您使用Java 8,则以下内容应该有效:

long count = "0 1 2 3 4.".chars().filter(Character::isWhitespace).count();

This will also work in Java 8 using Eclipse Collections : 这也适用于使用Eclipse Collections的 Java 8:

int count = Strings.asChars("0 1 2 3 4.").count(Character::isWhitespace);

Note: I am a committer for Eclipse Collections. 注意:我是Eclipse Collections的提交者。

\\t will match tabs, rather than spaces and should also be referred to with a double slash: \\\\t . \\t将匹配制表符,而不是空格,也应该用双斜杠引用: \\\\t You could call s.split( " " ) but that wouldn't count consecutive spaces. 你可以调用s.split( " " )但不会计算连续的空格。 By that I mean... 我的意思是......

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 Lang is your friend for this one. Commons Lang是你的朋友。

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

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。

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 . 此外,标签的数量将比arr.length少一个。

另一种使用正则表达式

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

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);

    }
}

The simple and fastest way to count spaces 计算空间的简单而快速的方法

 String fav="foo hello me hi";
for( int i=0; i<fav.length(); i++ ) {
        if(fav.charAt(i) == ' ' ) {
            counter++;
        }
    }

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;
}

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);

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);
public static void main(String[] args) {
    String str = "Honey   dfd    tEch Solution";
    String[] arr = str.split(" ");
    System.out.println(arr.length);
    int count = 0;
    for (int i = 0; i < arr.length; i++) {
        if (!arr[i].trim().isEmpty()) {
            System.out.println(arr[i]);
            count++;
        }
    }
    System.out.println(count);
}
public static void main(String[] args) {  
Scanner input= new Scanner(System.in);`

String data=input.nextLine();
int cnt=0;
System.out.println(data);
for(int i=0;i<data.length()-1;i++)
{if(data.charAt(i)==' ')
    {
        cnt++;
    }
}

System.out.println("Total number of Spaces in a given String are " +cnt);
}

This program will definitely help you. 这个程序肯定会帮助你。

class SpaceCount
{

    public static int spaceCount(String s)
    { int a=0;
        char ch[]= new char[s.length()];
        for(int i = 0; i < s.length(); i++) 

        {  ch[i]= s.charAt(i);
            if( ch[i]==' ' )
            a++;
                }   
        return a;
    }


    public static void main(String... s)
    {
        int m = spaceCount("Hello I am a Java Developer");
        System.out.println("The number of words in the String are :  "+m);

    }
}

The most precise and exact plus fastest way to that is : 最精确,最准确,最快的方法是:

String Name="Infinity War is a good movie";

    int count =0;

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

    System.out.println(count);

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM