Java面向对象-String类综合案例

“ aB232 23 &*( s2 ”指定字符串,要求去掉前后空格,然后分别统计其中英文字符,空格,数字和其他字符的个数;

思路:首先去掉前后空格,我们查找api文本,可以找到trim()方法;

要统计的话,我们遍历字符串,然后通过if判断来统计各种字符的个数;

我们给下参考代码:

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

36

37

38

39

package com.java.chap03.sec08;

public class Demo09 {

    public static void main(String[] args) {

        String str=" aB232 23 &*( s2 ";

        String newStr=str.trim(); // 去掉前后空格

        System.out.println("str="+str);

        System.out.println("newStr="+newStr);

         

        int yingWen=0// 英文个数

        int kongGe=0// 空格个数

        int shuZi=0// 数字个数

        int qiTa=0// 其他

         

        for(int i=0;i<newStr.length();i++){

            char c=newStr.charAt(i);

            // 判断英文字符

            if((c>='a'&&c<='z')||(c>='A'&&c<='Z')){

                yingWen++;

                System.out.println("英文字符:"+c);

            }else if(c>='0'&&c<='9'){

                shuZi++;

                System.out.println("数字字符:"+c);

            }else if(c==' '){

                kongGe++;

                System.out.println("空格字符:"+c);

            }else{

                qiTa++;

                System.out.println("其他字符:"+c);

            }

        }

         

        System.out.println("英文个数:"+yingWen);

        System.out.println("空格个数:"+kongGe);

        System.out.println("数字个数:"+shuZi);

        System.out.println("其他个数:"+qiTa);

    }

}

猜你喜欢

转载自blog.csdn.net/weixin_41934292/article/details/88322978