标签:java上级题 java算法 字符个数统计 character
对输入的字符串,分别统计字符串内英文字母,空格,数字和其它字符的个数。
import java.util.Scanner;
public class CharacterCount {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入要统计的字符串");
String input = sc.nextLine();
// 避免直接回车,输入为空的情况
while ("".equals(input)) {
System.out.println("您刚才输入为空,请输入要统计的字符串");
input = sc.nextLine();
}
// 定义计数器,来统计英文字符,数字,空格和其它字符的个数
int egCount = 0, numCount = 0, blankCount = 0, otherCount = 0;
// method 1 字符比较
for (Character ch : input.toCharArray()) {
// 判断英文字符
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
egCount ++;
}
// 判断空格
else if (ch == ' ') {
blankCount ++;
}
// 判断数字
else if (ch >= '0' && ch <= '9') {
numCount ++;
}
// 其它字符
else {
otherCount ++;
}
}
// 输出统计结果
System.out.println("刚才的输入中");
System.out.println("英文字符个数: " + egCount);
System.out.println("空格个数: " + blankCount);
System.out.println("数字个数: " + numCount);
System.out.println("其它字符: " + otherCount);
sc.close();
}
}
import java.util.Scanner;
public class CharacterCount {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入要统计的字符串");
String input = sc.nextLine();
// 避免直接回车,输入为空的情况
while ("".equals(input)) {
System.out.println("您刚才输入为空,请输入要统计的字符串");
input = sc.nextLine();
}
// 定义计数器,来统计英文字符,数字,空格和其它字符的个数
int egCount = 0, numCount = 0, blankCount = 0, otherCount = 0;
// method2 使用Character静态方法判断
for (Character ch : input.toCharArray()) {
// 判断英文字符
if (Character.isLetter(ch)) {
egCount ++;
}
// 判断空格
else if (Character.isWhitespace(ch)) {
blankCount ++;
}
// 判断数字
else if (Character.isDigit(ch)) {
numCount ++;
}
// 其它字符
else {
otherCount ++;
}
}
// 输出统计结果
System.out.println("刚才的输入中");
System.out.println("英文字符个数: " + egCount);
System.out.println("空格个数: " + blankCount);
System.out.println("数字个数: " + numCount);
System.out.println("其它字符: " + otherCount);
sc.close();
}
}标签:java上级题 java算法 字符个数统计 character
原文地址:http://blog.csdn.net/magi1201/article/details/45723179