標籤:amp sys class else 多少 main out 次數 sum
1、需求:擷取字串中的每一個字元
分析:
A:如何能夠拿到每一個字元呢?
char charAt(int index)
B:我怎麼知道字元到底有多少個呢?
int length()
public class StringTest { public static void main(String[] args) { // 定義字串 String s = "helloworld";for (int x = 0; x < s.length(); x++) { // char ch = s.charAt(x); // System.out.println(ch); // 僅僅是輸出,我就直接輸出了 System.out.println(s.charAt(x)); } }}
2、需求:統計一個字串中大寫字母字元,小寫字母字元,數字字元出現的次數。(不考慮其他字元)
舉例:
"Person1314Study"
分析:
A:先定義三個變數
bignum、samllnum、numbersum
B:進行數組的遍曆
for()、lenght()、charAt()
C:判斷各個字元屬於三個變數哪個
bignum:(ch>=‘A‘ && ch<=‘Z‘)
smallnum:(ch>=‘a‘ && ch<=‘z‘)
numbersum:(ch>=‘0‘ && ch<=‘9‘)
D:輸出
public class StringTest3 { public static void main(String[] args) { //定義一個字串 String s = "Person1314Study"; //定義三個統計變數 int bignum = 0; int smallnum = 0; int numbernum = 0; //遍曆字串,得到每一個字元。 for(int x=0;x<s.length();x++){ char ch = s.charAt(x); //判斷該字元到底是屬於那種類型的 if(ch>=‘A‘ && ch<=‘Z‘){ bignum++; } else if(ch>=‘a‘ && ch<=‘z‘){ smallnum++; } else if(ch>=‘0‘ && ch<=‘9‘){ numbernum++; } } //輸出結果。 System.out.println("含有"+bignum+"個大寫字母"); System.out.println("含有"+smallnum+"個小寫字母"); System.out.println("含有"+numbernum+"個數字"); }}
java字串的遍曆以及字串中各類字元的統計