Count words in a line - blank space

I am working on a program that will count words that are typed or inserted into the text area. He correctly counts words if he does not have double space. I use the split method for this and use a for loop to count words for objects.

here is the simplest form of part of the code that caused some problems ...


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 contains a space, but how I do it does not work.

I want it to be output as follows

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

the words; 3

but the result

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

Any suggestions on how I can solve this? or in what part did I have a problem? thank you in advance.

+4
source share
3 answers

split expects regular expression. Use it.

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

You need to change the line if(s.equals(" ")) to if(s.equals("")) (without a space). The reason is because split gives you an array of what is between spaces, and there is nothing between these two spaces.

+2
source

When you get an empty string from String.split , you can use String.equals to check the contents of the string in the returned array:

 if (s.equals("")) { ... 

Output:

 --Java skipped space --C++ --C# 
+1
source

Source: https://habr.com/ru/post/1437022/


All Articles