posts - 397,comments - 0,views - 25332

String当中与转换相关的常用方法有:

public char[] toCharArray():将当前字符串拆分成为字符数组作为返回值。

public byte[] getBytes():获得当前字符串底层的字节数组。

public String replace(CharSequence oldstring,CharSequence newString):

将所有出现的老字符串替换成为新的字符串,返回替换之后的结果新字符串。

 

代码举例:

复制代码
    public static void main(String[] args) {

        char[] chars = "Hello".toCharArray();
        System.out.println(chars[0]);
        System.out.println(chars.length);
        System.out.println("==========");
        byte[] bytes = "abc".getBytes();
        for (int i = 0; i < bytes.length; i++) {
            System.out.println(bytes[i]);
        }
        System.out.println("=========");
        String s1 = "How do you do?";
        String o = s1.replace("o", "*");
        System.out.println(s1);
        System.out.println(o);

        String lang = "收到收到收到收到是的是的是的是的是的是!!!";
        String dss = lang.replace("dss", "*****");
        System.out.println(dss);
    }
复制代码

键盘输八一个字符串,并且统计其中各种字符出现的次数。

种类有:大写字母、小写字母、数字、其他

思路:

既然用到键盘输入,肯定是scanner

键盘输入的是字符串,那么:String str = sc.next( );

定义四个变量,分别代表四种字符各自的出现次数。

需要对字符串一个字、一个字检查,String-->char[],方法就是toCharArray()

遍历char[]字符数组,对当前字符的种类进行判断,并且用四个变量进行++动作。

打印输出四个变量,分别代表四种字符出现次数。

复制代码
 Scanner scanner = new Scanner(System.in);
        String next = scanner.next();

        int a = 0;
        int b = 0;
        int c = 0;
        int d = 0;
        char[] chars = next.toCharArray();
        for (int i = 0; i <chars.length; i++) {
            char ch = chars[i];
            if ('A'<= ch && ch <= 'z'){
                a++;
            }else if ('a'<=ch && ch <= 'z'){
                b++;
            }else if ('0'<= ch && ch<= '9'){
                c++;
            }else {
                d++;
            }
        }
        System.out.println(a);
        System.out.println(b);
        System.out.println(c);
        System.out.println(d);
复制代码

 

posted on   淤泥不染  阅读(36)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5

点击右上角即可分享
微信分享提示