java - Calculate number of words in an ArrayList while some words are on the same line -


i'm trying calculate how many words arraylist contains. know how if every words on separate line, of words on same line, like:

hello there blah cats dogs 

so i'm thinking should go through every entry , somehow find out how many words current entry contains, like:

    public int numberofwords(){     for(int = 0; < arraylist.size(); i++) {         int words = 0;         words = words + (number of words on current line);     //words should equal 5     } return words; } 

am thinking right?

you should declare , instantiate int words outside of loop int not reassign during every iteration of loop. can use for..each syntax loop through list, eliminate need get() items out of list. handle multiple words on line split string array , count items in array.

public int numberofwords(){     int words = 0;     for(string s:arraylist) {                words += s.split(" ").length;     }     return words; } 

full test

public class stacktest {      public static void main(string[] args) {         list<string> arraylist = new arraylist<string>();         arraylist.add("hello there");         arraylist.add("blah");         arraylist.add("   cats    dogs");         arraylist.add(" ");         arraylist.add(" ");         arraylist.add(" ");          int words = 0;         for(string s:arraylist) {             s = s.trim().replaceall(" +", " "); //clean string             if(!s.isempty()){ //do not count empty strings                words += s.split(" ").length;             }         }         system.out.println(words);     } } 

Popular posts from this blog

How to calculate SNR of signals in MATLAB? -

c# - Attempting to upload to FTP: System.Net.WebException: System error -

ios - UISlider customization: how to properly add shadow to custom knob image -