Java基礎語法題(07):字符串中字符的分類統計

題目描述:

輸入一行字符,分別統計出其中英文字母、空格、數字和其它字符的個數。



<code>    package Demo07Character_Count;
import java.util.Scanner;
public class Caracter_Count {
/**
* 輸入一行字符,分別統計出其中英文字母、空格、數字和其它字符的個數。
*/
/*
分析:這道題沒有說要統計每個字符的個數,而只是統計英文字母,空格,數字和其它字符的個數,所以,我們用簡單的
變量來計數就可以了。可以考慮把用戶輸入的字符串toCharArray()一下,再一一對比判斷。
*/
public static void main(String[] args) {
System.out.println("請輸入一段字符串……");
Scanner sc = new Scanner(System.in);
// 獲取用戶輸入的字符串,因為Scanner類的next()方法遇到空格或enter會終止,所以這裡用nextLine()方法獲取整行
String str = sc.nextLine();
System.out.println(str);
// 分解
char[] chars = str.toCharArray();
// 定義四個變量來計數
int letters = 0;
int numbers = 0;
int spaces = 0;
int others = 0;
// 遍歷數組並計數
for (int i = 0; i < chars.length; i++) {
if ((chars[i] >= 'A') && (chars[i]) <= 'Z') {
letters++;

} else if ((chars[i] >= 'a') && (chars[i]) <= 'z') {
letters++;
} else if ((chars[i] >= '0') && (chars[i]) <= '9') {
numbers++;
} else if (chars[i] == ' ') {
spaces++;
} else {
others++;
}
}
System.out.println("您剛輸入的字符串中英文字符有:" + letters + "個。");
System.out.println("數字字符有:" + numbers + "個。");
System.out.println("空格字符有:" + spaces + "個。");
System.out.println("其它字符有:" + others + "個。");
}
}/<code>


分享到:


相關文章: