Problem07 处理字符串

Problem07 处理字符串

题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。

程序分析:利用while 语句,条件为输入的字符不为' '.

 1 import java.util.*;
 2 
 3 public class Problem07 {
 4     //题目:输入一行字符,分别统计出其中英文字母ch、
 5     //空格blank、数字num和其它字符other的个数。
 6     //程序分析:利用while语句,条件为输入的字符不为'
'.
 7     public static void main(String args[]) {
 8         int ch=0, blank=0, num=0, other=0;
 9         System.out.println("请输入一行字符:");
10         Scanner s = new Scanner(System.in);
11         String str = s.nextLine();
12         //System.out.println(str);
13         //将输入的字符串转换为字符数组
14         char[] cha=str.toCharArray();
15 //        System.out.println(cha.length);
16         
17         int index = 0;
18         while(cha[index] != '
' && index<(cha.length-1)) {
19             //判断是否为英文字符
20             if(('a'<=cha[index] && cha[index]<='z') || ('A'<=cha[index] && cha[index]<='Z')) {
21                 ch++;
22             }
23             //判断是否为空格
24             else if(cha[index]==' ') {
25                 blank++;
26             }
27             //判断是否为数字
28             else if('0'<=cha[index] && cha[index]<='9') {
29                 num++;
30             }
31             else
32                 //其他字符
33                 other++;
34             
35             index++;
36         }
37         
38         System.out.println("英文字符数:"+ch);
39         System.out.println("空格个数:"+blank);
40         System.out.println("数字字符数:"+num);
41         System.out.println("其他字符数:"+other);
42         s.close();
43     }
44 }

输出结果:

1 请输入一行字符:
2 hello world this is No.7 talking
3 英文字符数:24
4 空格个数:5
5 数字字符数:1
6 其他字符数:1