25

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");
println("Number of spaces are: "+arr.length);
count++;
Adil Hussain
  • 30,049
  • 21
  • 112
  • 147
kamweshi
  • 375
  • 1
  • 6
  • 15

17 Answers17

37

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

In your case you tried to split the string using \t, i.e. TAB. You will get the right result if you use " " instead. Using \s may be confusing since it matches all whitespaces, i.e. regular spaces and TABs.

Adil Hussain
  • 30,049
  • 21
  • 112
  • 147
AlexR
  • 114,158
  • 16
  • 130
  • 208
24

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
  • 412,405
  • 93
  • 575
  • 722
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,329
  • 1
  • 30
  • 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
  • 9,018
  • 2
  • 20
  • 36
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,458
  • 2
  • 36
  • 44
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,458
  • 19
  • 23
2

Another way using regular expressions

int length = text.replaceAll("[^ ]", "").length();
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
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,248
  • 3
  • 23
  • 39
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,334
  • 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;
}
  • 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
  • 35,919
  • 9
  • 100
  • 137
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
  • 15,342
  • 16
  • 114
  • 137
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,248
  • 3
  • 23
  • 39
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,762
  • 2
  • 16
  • 27
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);
     }
}