String類有許多獲取方法,API文檔里面可查看。針對獲取方法,給出小案例。
/** 需求:遍歷獲取字符串中的每一個字符* 分析:
用到兩個方法:char charAt(int index) 表示獲取字符串指定索引的字符int length() 表示獲取字符串的長度*/
public class StringTest {public static void main(String[] args) {// 定義字符串String s = "helloworld";//思考,要想獲取每個索引而且效率比較高,用for循環改進。for (int x = 0; x < s.length(); x++) {// char ch = s.charAt(x);// System.out.println(ch);// 僅僅是輸出,我就直接輸出了System.out.print(s.charAt(x));}}
}
再寫一個小案例:
/** 需求:統計一個字符串中大寫字母字符,小寫字母字符,數字字符出現的次數。(不考慮其他字符)* 舉例:* "Hello123World"* 結果:* 大寫字符:2個* 小寫字符:8個* 數字字符:3個* * 分析:* 前提:字符串要存在* A:定義三個統計變量* bigCount=0* smallCount=0* numberCount=0* B:遍歷字符串,得到每一個字符。* length()和charAt()結合* C:判斷該字符到底是屬于那種類型的* 大:bigCount++* 小:smallCount++* 數字:numberCount++* 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+"個");}
}
其實有更簡單的方式獲取大小寫數字個數的方法。后面會寫。