Search code examples
javastringsplitwordscounting

counting words in string - skipping double space


I am working on a program that will count words that is typed or pasted in the text area. It counts the words correctly if it doesn't have a double space. I use the split method for this and uses the for loop for objects to count the words.

here is the simplest form of the part of the code that got some problem...


 public static void main(String[] args) {
    String string = "Java  C++ C#";
    String[] str;
    int c=0;
    str = string.split(" ");
    for(String s:str){
        if(s.equals(" "))
            System.out.println("skipped space");
        else{
            System.out.println("--"+s);
            c++;
        }
    }
    System.out.println("words; " + c);
}

im trying to check if the string contained in the object s is a space but how I do it didn't work.

I want it to output like this

--Java
skipped space
--C++
--C#

words; 3

but the result is

--Java
--
--C++
--C#
words; 4

Any Suggestions on how can i solve this? or which part i got a problem? thanks in advance.


Solution

  • split expects a regular expression. Use it's power.

    str = string.split(" +");
    
    //more sophisticated
    str = string.split("\\s+");
    
    • \s matches any whitespace (not just space, but tabs. newline etc.)
    • + means "one or more of them"
    • The first backslash is needed to escape the second to remove the special meaning inside the string