把随机输入的一句话比如: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 == null) throw 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]);
}
}
}
转载于:https://www.cnblogs.com/gzhnan/articles/285991.html