void setup(){
String s = "";
int count = count_words(s);
println(count);
s = "Welcome";
count = count_words(s);
println(count);
s = " Welcome to Thailand";
count = count_words(s);
println(count);
}
int count_words(String a){
int words;
int start=-1,end=-1;
if(a.length() != 0){
words=1;
if(a.charAt(0)==' '){
for(int i=0;(i<a.length())&&(start<0);i++){
if((a.charAt(i)==' ')&&(a.charAt(i+1)!=' ')){
start = i+1;
}
}
}
else {start = 0;}
if(a.charAt(a.length()-1)==' '){
for(int i=a.length()-1;(i>=0)&&(end<0);i--){
if((a.charAt(i)==' ')&&(a.charAt(i-1)!=' ')){
end = i-1;
}
}
}
else {end = a.length();}
for(int i=start;i<end;i++){
if((a.charAt(i)==' ')&&(a.charAt(i+1)!=' ')){
words = words+1;
}
}
}
else {words = 0;}
return words;
}
โค้ดข้างล่าง ลองทำอีกวิธี แต่ยังบัคอยู่
/*
int count_words(String a){
a = trim(a);
println(a);
String[] x = split(a,' ');
int n = x.length;
return n;
}
*/