1 2 Previous Next 18 Replies Latest reply: Jul 28, 2009 2:14 PM by 800282 RSS

    What is my String.split() not catching here?

    843789
      Hello,
      I am trying to implement the wordcount below. Most of the time it works great, the content matches the wc utility.
      Occasionally though it splits in a manner that creates a whitespace word. Any suggestions? Is there a better algorithm to switch to? This had appeared to be a clean approach up until these issues.
      public static int wordCounter(File inFile) throws FileNotFoundException, IOException{
                          
                int count = 0;
                
                BufferedReader inReader = new LineNumberReader(new InputStreamReader(new FileInputStream(inFile)));
                          
                try{               
                     String lineString;
                     String[] lineWords;     
                     
                     //while not the end of the file               
                     while( (lineString = inReader.readLine()) != null){
                          
                          lineString.trim();
                          lineWords = lineString.split("\\s+");
                          
                          count += lineWords.length;                    
                          
                     }
                     
                } finally{
                     //close the BufferedReader
                     if(inReader != null){
                          inReader.close();
                     }
                }
                //return the count
                return count;
                
           }
        1 2 Previous Next