+ 1
Word count in java
How to count number of words in a string with regex using Java
2 Réponses
+ 5
yes kambiz is correct to do it in Java
public class Wordcount {
static int i,word=0,res;
static int wordcount(String s) {
char ch[]= new char[s.length()]; for(i=0;i<s.length();i++) {
ch[i]= s.charAt(i);
if( ((i>0)&&(ch[i]!=' ')&&(ch[i-1]==' ')) || ((ch[0]!=' ')&&(i==0)) ) word++; }
return word; }
this is not by regax to use it in regax simply add function to count " " string as by index method too of Java
you can also consider the split elements as done in regax this way you can count it directly
+ 3
Use square brackets, not parentheses:
str[i] === " "
Or charAt:
str.charAt(i) === " "
You could also do it with .split():
return str.split(' ').length;