练习:字符串

1.将一个字符串逆序输出 例如: abcd  --> dcba

public static void main(String[] args) {
        String s1 = "abcd";
        char[] c = s1.toCharArray();
        char[] a = new char[4];
        int j =3;
        for (int i = 0; i < c.length; i++) {
            a[j--] = c[i];
        }
        String s2 = new String(a);
        System.out.println(a);
}

2.统计一个字符串中出现的大写字母,小写字母各自的个数

public static void main(String[] args) {
        System.out.println("请输入一串字母(含大小写):");
        Scanner scanner = new Scanner(System.in);
        String s1 = scanner.next();
        char[] c = s1.toCharArray();
        int small = 0;
        int large = 0;
        for (int i = 0; i < s1.length(); i++) {
            if(c[i]>='A' && c[i]<='Z'){
                large++;
            }else if(c[i]>='a' && c[i]<='z'){
                small++;
            }
        }
        System.out.println("大写字母个数:"+large);
        System.out.println("小写字母个数:"+small);
    }

3.判断一个字符串是否对称,例如"abccba"

    public static void Symmetric(String s1){
        char[] c = s1.toCharArray();
        int len = c.length;
        int count = c.length - 1;
        boolean flag=false;
        for (int i = 0; i < (c.length-1)/2; i++) {
            if(c[i] != c[count--]){
                flag=false;
               break;
            }
        }
        if(flag){
            System.out.println("对称");
        }else {
            System.out.println("不对称");
        }
    }

    public static void main(String[] args) {
        System.out.println("输入一串字符串:");
        Scanner scanner = new Scanner(System.in);
        String s1 = scanner.next();
        Symmetric(s1);
    }

4.定义一个用于截取文件后缀名的方法, 传入一个字符串的文件名( hello.java),返回一个字符串.

public static void main(String[] args) {
        System.out.println("请输入一个字符串的文件名:");
        Scanner scanner = new Scanner(System.in);
        String s1 = scanner.next();
        char[] c1 = s1.toCharArray();
        char[] c2 = new char[20];
        int j = 0;
        for (int i = 0; i < s1.length(); i++) {
            if(c1[i]=='.'){
                for (int k = 0; k < s1.length(); k++) {
                    k = ++i;
                    c2[j++] = c1[k];
                }
            }
        }
        String s2 = new String(c2);
        System.out.println("文件后缀名为:"+s2);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值