本文實例為大家分享了java字符串遍歷,以及java統計字符串中各類字符的具體代碼,供大家參考,具體內容如下
1、需求:獲取字符串中的每一個字符
分析:
A:如何能夠拿到每一個字符呢?
char charAt(int index)
B:我怎么知道字符到底有多少個呢?
int length()
1
2
3
4
5
6
7
8
9
10
11
12
|
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:輸出
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
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+ "個數字" ); } } |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://www.cnblogs.com/shuilangyizu/p/8460885.html