Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 288
Katherine Avatar asked Dec 26 '22 17:12

Katherine


2 Answers

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
like image 99
Prinzhorn Avatar answered Jan 09 '23 17:01

Prinzhorn


You need to change the line if(s.equals(" ")) to if(s.equals("")) (with no space). The reason is that split gives you an array of what thare is between the spaces, and there is nothing between the two spaces.

like image 32
LeeNeverGup Avatar answered Jan 09 '23 18:01

LeeNeverGup