Write a method called wordCount that accepts a String as its parameter and returns the number of words in the String. A word is a sequence of one or more nonspace characters
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)
Splits this string around matches of the given regular expression.
public static int wordCount(String s){
int counter=0;
for(int i=0;i<=s.length()-1;i++){
if(Character.isLetter(s.charAt(i))){
counter++;
for(;i<=s.length()-1;i++){
if(s.charAt(i)==' '){
i++;
break;
}
}
}
}
return counter;
}
This is what you need if don't use the predefined function. I have tested it by myself. Please let me know if there is any bugs!
My few solutions:
public static int wordcount1(String word) {
if (word == null || word.trim().length() == 0) {
return 0;
}
int counter = 1;
for (char c : word.trim().toCharArray()) {
if (c == ' ') {
counter++;
}
}
return counter;
}
//
public static int wordcount2(String word) {
if (word != null || word.length() > 0) {
return word.trim().length()
- word.trim().replaceAll("[ ]", "").length() + 1;
} else {
return 0;
}
}
// Recursive
public static int wordcount3(String word) {
if (word == null || word.length() == 0) {
return 0;
}
if (word.charAt(0) == ' ') {
return 1 + wordcount3(word.substring(1));
}
return wordcount3(word.substring(1));
}
//
public static int wordcount4(String word) {
if (word == null || word.length() == 0) {
return 0;
}
String check = word.trim();
int counter = 1;
for (int i = 0; i < check.length(); i++) {
if (i > 0 && Character.isSpaceChar(check.charAt(i))
&& !Character.isSpaceChar(check.charAt(i - 1))) {
counter++;
}
}
return counter;
}