+ 1

Word count in java

How to count number of words in a string with regex using Java

30th Nov 2016, 10:09 PM
Sagar Mamidala
Sagar Mamidala - avatar
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
1st Dec 2016, 3:58 AM
Sandeep Chatterjee
+ 3
Use square brackets, not parentheses: str[i] === " " Or charAt: str.charAt(i) === " " You could also do it with .split(): return str.split(' ').length;
30th Nov 2016, 10:16 PM
Hooman Hassanzadeh
Hooman Hassanzadeh - avatar