Java实现统计字符串中的字母和数字分别有多少个
需求
编写程序,由键盘录入一个字符串,统计字符串中英文字母和数字分别有多少个。比如:Hello12345World中字母:10个,数字:5个。
设计思路
查看Scanner类和String类的API,遍历字符串,分别统计字母和数字的个数
代码实现1
package com.itheima.APITest.Test04;
import java.util.Scanner;
/*
请编写程序,由键盘录入一个字符串,
统计字符串中英文字母和数字分别有多少个。
比如:Hello12345World中字母:10个,数字:5个。
*/
public class Demo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个字符串:");
//public String nextLine()
//将此扫描仪推进到当前行并返回跳过的输入。
String s = sc.nextLine();
//定义统计字母的变量
int charCount = 0;
//定义统计数字的变量
int numCount = 0;
//遍历字符串
//public int length()
//返回此字符串的长度。
for (int i = 0; i < s.length(); i++) {
//取出字符串中的字符,判断是否为字母
//public char charAt(int index)
//返回指定索引处的char值。 指数范围从0到length() - 1 。 序列的第一个char值是索引0 ,下一个索引为1 ,依此类推,就像数组索引一样。
if ((s.charAt(i) >= 'A' && s.charAt(i) <= 'Z') || (s.charAt(i) >= 'a' && s.charAt(i) <= 'z')) {
charCount++;
} else if (s.charAt(i) >= '0' && s.charAt(i) <= '9') {//判断字符串中的字符是否为数字
numCount++;
}
}
System.out.println("字母:" + charCount + "数字:" + numCount);
}
}
代码实现2
由于判断字符是否为字母要考虑大小写的情况,太过复杂,寻求简化的途径,翻看String类的API文档,优化后的代码如下:
package com.itheima.APITest.Test04;
import java.util.Scanner;
/*
统计字符串中的字母和数字的个数,为了简化判断,将其字母全部转换为小写字母
查看String类的API,实现
*/
public class Demo02 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个字符串:");
String s = sc.nextLine();
//public String toLowerCase()
//将此String所有字符转换为小写,使用默认语言环境的规则。
String s1 = s.toLowerCase();
int charCount = 0;
int numCount = 0;
for (int i = 0; i < s1.length(); i++) {
if (s1.charAt(i) >= 'a' && s1.charAt(i) <= 'z') {
charCount++;
} else if (s1.charAt(i) >= '0' && s1.charAt(i) <= '9') {
numCount++;
}
}
System.out.println("字母有:" + charCount + "个");
System.out.println("数字有:" + numCount + "个");
}
}