各位高手,这个是我写的一道题目的结果:题目是要求找一段英文文章存储为文本文件,计算出这个文件含有多少个英文单词(提示:单词是用空格或者标点符号分隔开的英文字母)。虽然我这一条的算法可能还有点问题,但我想问的是在我打的感叹号标记的那一行的StringTokenizer的构造的第二个参数改成"\\s"就不行了,这个是为什么,难道"\\s"不是空格的正则表达式了吗import java.io.*;
import java.util.*;
public class CalculateWordNums
{
  public static int calculateWordNums(String fileName) throws FileNotFoundException, IOException
  {
    FileReader fr = new FileReader(fileName);
    BufferedReader br = new BufferedReader(fr);
    //int b = 0;
    int count = 0;
    String str = null;
    while((str = br.readLine()) != null)
    {
      StringTokenizer st = new StringTokenizer(str, " ");  //!!!!!!!!!!!!!!!!!!!!!!!!!
      while(st.hasMoreTokens())
      {
        str = st.nextToken();
        if (Character.isLetter(str.charAt(0)))
          count++;
      }
    }    return count;
  }  public static void main(String[] args)
  {
    try
    {
      int nums = calculateWordNums("novel.txt");
      System.out.println(nums);
    }
    catch (FileNotFoundException e) {}
    catch (IOException e)
    {
      e.printStackTrace();
    }
  }
}

解决方案 »

  1.   


            FileReader   fr   =   new   FileReader(fileName); 
            BufferedReader   br   =   new   BufferedReader(fr); 
            //int   b   =   0; 
            int   count   =   0; 
            String   str   =   null; 
            String   string="";
            while((str   =   br.readLine())   !=   null) 
            { 
                //StringTokenizer   st   =   new   StringTokenizer(str,   "   ");     //!!!!!!!!!!!!!!!!!!!!!!!!! 
                  //while(st.hasMoreTokens()) 
                //{ 
                //    str   =   st.nextToken(); 
                //    if   (Character.isLetter(str.charAt(0))) 
                //        count++; 
                //} 
                string+=str;
            } 
            count=string.split("[\\s\\W]+").length;