1 /*7 【程序 7 处理字符串】 2 题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。 3 程分析:利用 while 语句,条件为输入的字符不为‘\n‘. 4 */ 5 6 /*分析: 7 * 1、百度到java语言中可使用.length(), charAt()来遍历字符串,这种方法的原理和c中的字符串数字类似 8 * 2、判断字符是什么类型,直接用ASCII码判断,且不需要写出来ASCII码是多少,如:字母直接用A~Z&a~z即可 9 * */ 10 11 12 package homework; 13 14 import java.util.Scanner; 15 16 public class _07 { 17 18 public static void main(String[] args) { 19 System.out.println("请输入一个包含英文字母、空格、数字和其它字符的字符串,并以回车键结束:"); 20 // 从键盘得到字符串 21 Scanner sc=new Scanner(System.in); 22 String s=sc.nextLine(); 23 24 // String s="ABCabc12312 &&*231"; //共6个字母,5个空格,8个数字,3个其他字符; 25 //声明4个计数器,分布统计字母,空格,数字和其他字符的个数 26 int word=0,balnk=0,num=0,other=0; 27 28 char c; 29 //使用for循环遍历字符串,并用ASCII码来判定字符是哪一类 30 for (int i = 0; i < s.length(); i++) { //序号从0开始,所有用"<"; 31 32 c=s.charAt(i); 33 // System.out.println(c); 34 while (c!=‘\n‘) { 35 if(((‘a‘<=c)&(c<=‘z‘))||((‘A‘<=c)&(c<=‘Z‘))) { 36 word++; 37 } 38 else if ((c>=‘1‘)&(c<=‘9‘)) { 39 num++; 40 } 41 else if (c==‘ ‘) { 42 balnk++; 43 } 44 else { 45 other++; 46 } 47 break; //break是结束while循环的,否者是死循环 48 } 49 50 } 51 System.out.println("字母个数为:"+word+"\n"+"空格个数为:"+balnk+"\n"+"数字个数为:"+num+"\n"+"其他符号个数为:"+other); 52 53 } 54 55 }
原文:https://www.cnblogs.com/scwyqin/p/12295266.html