统计字符串中的英文字母、空格、数字和其它字符的个数
- /**
- * 统计字符串中各类型字符的个数
- */
- import java.util.*;
- import java.io.*;
- //import java.io.InputStream;
- public class Task140_6{
- public static void main(String[] args) throws Exception{//需要抛出异常
- BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
- System.out.println("please input character string:");
- String s = br.readLine();
- //Task140_6 t = new Task140_6();
- countSum(s);
- }
- public static void countSum(String s){
- int alphabet = 0;
- int blankspace = 0;
- int number = 0;
- int other = 0;
- for(int i = 0;i < s.length();i++){
- char c = s.charAt(i);//charAt()方法返回索引i处的char字符
- if(c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z') alphabet++;
- else if(c == ' ') blankspace++;
- else if(c >= '0' && c <= '9') number++;
- else other++;
- }
- System.out.println("字母个数为:" + alphabet);
- System.out.println("空格个数为:" + blankspace);
- System.out.println("数字个数为:" + number);
- System.out.println("其他字符个数为:" + other);
- }
- }
复制代码
|
|