22

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++;
kamweshi
  • 325
  • 1
  • 5
  • 15

17 Answers17

36

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

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 \s may be confusing since it matches all whitepsaces - regular spaces and TABs.

AlexR
  • 111,884
  • 15
  • 126
  • 200
23

Here is 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

You can use a stream too:

long spaces = s.chars().filter(c -> c == (int)' ').count();
ToWy
  • 23
  • 7
Bohemian
  • 389,931
  • 88
  • 552
  • 692
8

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.

Konstantin Pribluda
  • 12,178
  • 1
  • 28
  • 35
5

\t will 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...

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.

int count = StringUtils.countMatches( inputString, " " );
chooban
  • 8,606
  • 2
  • 19
  • 35
4

If you use Java 8, the following should work:

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

This will also work in Java 8 using Eclipse Collections:

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

Note: I am a committer for Eclipse Collections.

Donald Raab
  • 6,038
  • 2
  • 33
  • 38
2

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.

nikhil500
  • 3,406
  • 18
  • 22
2

Another way using regular expressions

int length = text.replaceAll("[^ ]", "").length();
Peter Lawrey
  • 513,304
  • 74
  • 731
  • 1,106
1

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

    }
}
Ahmad Al-Kurdi
  • 2,092
  • 2
  • 19
  • 36
1

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++;
        }
    }
Syed Danish Haider
  • 1,244
  • 11
  • 15
1

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;
}
Kurt Kaylor
  • 2,722
  • 13
  • 18
  • 2
    The ternary operator really isn't needed here, it would be clearer to just have a single if and ignore the case when the `char` isn't whitespace. – Jeffrey Mar 11 '12 at 14:55
1

A solution using 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);
Adam
  • 34,473
  • 9
  • 94
  • 130
0

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);
James Drinkard
  • 14,670
  • 15
  • 108
  • 135
0
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);
}
UTKAL
  • 1
  • 1
0
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);
}
HSN
  • 1
  • 1
0

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

    }
}
Ahmad Al-Kurdi
  • 2,092
  • 2
  • 19
  • 36
0

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);
vegetarianCoder
  • 2,254
  • 2
  • 15
  • 24
0
import java.util.Scanner;
import java.io.*;

public class Main {
       public static void main(String args[]) {
  
          Scanner sc = new Scanner(System.in).useDelimiter("\n");
          String str = sc.next();
          int spaceCount=0;
          str = str.toLowerCase();    
        
          for(int i = 0; i < str.length(); i++) {
              if(str.charAt(i)==' '){
                  spaceCount++;
              }
          }
          System.out.println("Number of spaces: "+ spaceCount);
     }
}