I am suppose to use methods in order to count number of words in the a sentence. I wrote this code and I am not quite sure why it doesn\'t work. No matter what I write, I on
Tested method - handles all inputs
public static void countwords() {
String s = " t ";
int count = 0;
int length = s.length()-1;
char prev = ' ';
for(int i=length; i>=0; i--) {
char c = s.charAt(i);
if(c != prev && prev == ' ') {
count++;
}
prev = c;
}
System.out.println(count);
}
Should you not have int count = 0;
instead of int count = 1;
, in case of blank sentences. If you're getting Java errors please could you add them to your question.
Actually, if you enter a sentence like:
"Hello World"
your code String sentence = in.next();
will only get the first word in the sentence i.e., Hello
.
So, you need to use in.nextLine()
in place of in.next()
to get the whole sentence i.e., Hello World
.
Use this method to calculate the number of words in a String:-
private int calculateWords(String s){
int count=0;
if(s.charAt(0)!=' ' || s.charAt(0)!=','){
count++;
}
for(int i=1;i<s.length();i++){
if((s.trim().charAt(i)==' ' && s.charAt(i+1)!=' ') || (s.trim().charAt(i)==',' && s.charAt(i+1)!=',')){
count++;
}
}
return count;
}
I'd suggest to use BreakIterator. This is the best way to cover not standard languages like Japanese where there aren't spaces that separates words.
Example of word counting here.
Here is one more method just using split
, trim
, equals
methods to improve code and performance.
This code will work with space as well.
public int countWords(String string){
String strArr [] = string.split("\\s");
int count = 0;
for (String str: strArr) {
if(!str.trim().equals("")){
count++;
}
}
return count;
}