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.
--Java
skipped space
--C++
--C#
--Java
--
--C++
--C#
words; 4
Any Suggestions on how can i solve this? or which part i got a problem? thanks in advance.
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"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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With