java 统计单词个数和标点符号

把随机输入的一句话比如:It's only a test!存放在一个char[]的数组中,统计char[]中的单词个数和标点符号的个数。

  package com.faintbear;

import java.io.
*;
public class Test{
    
public static void main(String[] args) throws Exception{
        BufferedReader br 
= new BufferedReader(new InputStreamReader(System.in));
        String str 
= br.readLine();
        
if(str == nullthrow new Exception("");
        
char[] c = str.toCharArray();
        
int words = 0;
        
int ip = 0;
        boolean wordflag 
= false;
        
for(int i=0;i<c.length;i++){
            
if((c[i]>='a' && c[i] <= 'z'|| (c[i] >= 'A' && c[i] <= 'Z')){
                
if(wordflag) {
                    
continue;
                }
else{
                    words
++;
                }

                wordflag 
= true;
            }
else{
                wordflag 
= false;
                
if(c[i] != ' ')
                    ip
++;
            }

        }

        System.
out.println("words=" + words);
        System.
out.println("ip=" + ip);
        
for(int i=0;i<c.length;i++)
        
{
          System.
out.print("c["+i+"]="+c[i]);
        }


    }

}
posted @ 2005-11-28 12:49  代码缔造的帝国  阅读(1691)  评论(1编辑  收藏  举报