java - Word count in a string -
ok,now know question has been asked many times , answered too, came across question , wrote this(poor piece of) code without taking clue previous answeres,and although giving me correct output,i can't decide if correct.
public class wordcount { public static void main(string[] args) throws ioexception { system.out.println("enter string"); bufferedreader br = new bufferedreader(new inputstreamreader(system.in)); string s1= br.readline(); s1 = s1+" "; string ns = ""; int count = 0; for(int = 0; < s1.length(); i++) { char ch = s1.charat(i); if(ch == ' ') { //ns = ns+ch; count++; } /*else { ns = ns+ch; }*/ } system.out.println("there "+count+" words in string"); } }
int linecount = yourstring.trim().split("\\s+").length;
the split()
function returns array containing tokens made splitting string in specified way. take string, split spaces , since it's array - take length of it. that's need count words. (the regex
\\s+
makes function split string @ every blank space, i.e., return array containing words.)
edit: point thomas
Comments
Post a Comment