package cn.itcast_04;
/*
* 需求:統計一個字串中大寫字母字元,小寫字母字元,數字字元出現的次數。(不考慮其他字元)
* 舉例:
* "Hello123World"
* 結果:
* 大寫字元:2個
* 小寫字元:8個
* 數字字元:3個
*
* 分析:
* 前提:字串要存在
* A:定義三個統計變數
* bigCount=0
* smallCount=0
* numberCount=0
* B:遍歷字串,得到每一個字元。
* length()和charAt()結合
* C:判斷該字元到底是屬於那種型別的
* 大:bigCount++
* 小:smallCount++
* 數字:numberCount++
*
* 這道題目的難點就是如何判斷某個字元是大的,還是小的,還是數字的。
* ASCII碼錶:
* 0 48
* A 65
* a 97
* 雖然,我們按照數字的這種比較是可以的,但是想多了,有比這還簡單的
* char ch = s.charAt(x);
*
* if(ch>='0' && ch<='9') numberCount++
* if(ch>='a' && ch<='z') smallCount++
* if(ch>='A' && ch<='Z') bigCount++
* D:輸出結果。
*
* 練習:把給定字串的方式,改進為鍵盤錄入字串的方式。
*/
public class StringTest2 {
public static void main(String[] args) {
//定義一個字串
String s = "Hello123World";
//定義三個統計變數
int bigCount = 0;
int smallCount = 0;
int numberCount = 0;
//遍歷字串,得到每一個字元。
for(int x=0; x<s.length(); x++){
char ch = s.charAt(x);
//判斷該字元到底是屬於那種型別的
if(ch>='a' && ch<='z'){
smallCount++;
}else if(ch>='A' && ch<='Z'){
bigCount++;
}else if(ch>='0' && ch<='9'){
numberCount++;
}
}
//輸出結果。
System.out.println("大寫字母"+bigCount+"個");
System.out.println("小寫字母"+smallCount+"個");
System.out.println("數字"+numberCount+"個");
}
}