java Please enter a line of string to count the number of English letters, spaces, numbers and other characters
import java.util.Scanner;
public class CountChars {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入一行字符串:");
String str = scanner.nextLine();
scanner.close();
int letterCount = 0; // 统计英文字母个数
int spaceCount = 0; // 统计空格个数
int digitCount = 0; // 统计数字个数
int otherCount = 0; // 统计其他字符个数
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z') {
letterCount++;
} else if (ch == ' ') {
spaceCount++;
} else if (ch >= '0' && ch <= '9') {
digitCount++;
} else {
otherCount++;
}
}
System.out.println("英文字母个数:" + letterCount);
System.out.println("空格个数:" + spaceCount);
System.out.println("数字个数:" + digitCount);
System.out.println("其他字符个数:" + otherCount);
}
}
result:
Please enter a line of string: vzvcxv zxcfdx fs 3254v
Number of English letters: 15
Number of spaces: 3
Number of digits: 4
Number of other characters: 0
Regular expression:
import java.util.Scanner;
public class CollectionCharsTestEl {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入一行字符串:");
String str = scanner.nextLine();
scanner.close();
int letterCount = 0; // 统计英文字母个数
int spaceCount = 0; // 统计空格个数
int digitCount = 0; // 统计数字个数
int otherCount = 0; // 统计其他字符个数
// 使用正则表达式匹配字符种类
String letterRegex = "[a-zA-Z]";
String spaceRegex = "\\s";
String digitRegex = "\\d";
for (int i = 0; i < str.length(); i++) {
String ch = str.substring(i, i + 1);
if (ch.matches(letterRegex)) {
letterCount++;
} else if (ch.matches(spaceRegex)) {
spaceCount++;
} else if (ch.matches(digitRegex)) {
digitCount++;
} else {
otherCount++;
}
}
System.out.println("英文字母个数:" + letterCount);
System.out.println("空格个数:" + spaceCount);
System.out.println("数字个数:" + digitCount);
System.out.println("其他字符个数:" + otherCount);
System.out.println( String.format("英文字母个数:%d, 空格个数:%d, 数字个数:%d, 其他字符个数:%d", letterCount,spaceCount,digitCount,otherCount));
}
}