需求:

拼接字符串 定义一个方法,把数组{1,2,3}按照指定个格式拼接成一个字符串。格式参照如下:[word1#word2#word3]。

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

 字符串练习题 随笔

package Demo2;

public class Demo06StringPractise {
    public static void main(String[] args) {
        int[] array = {1, 2, 3};
        System.out.println(fromArrayToString(array));//[word1#word2#word3]
    }

    // 拼接字符串的方法
    public static String fromArrayToString(int[] array) {
        String str = "[";
        // 遍历数组
        for (int i = 0; i < array.length; i++) {
            // 判断是不是最后一个元素
            if (i == array.length - 1) {
                str += "word" + array[i] + "]";
            } else {
                str += "word" + array[i] + "#";
            }
        }
        return str;
    }
}

统计字符个数

键盘录入一个字符,统计字符串中大小写字母及数字字符个数

package Demo2;

import java.util.Scanner;

public class Demo07StringCount {

        public static void main(String[] args) {
             //键盘录入一个字符串数据
            Scanner sc = new Scanner(System.in);
            System.out.println("请输入一个字符串数据:");
            String s = sc.next();
             //定义三个统计变量,初始化值都是0
            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') {
                    bigCount++;
                }else if(ch>='a'&&ch<='z') {
                    smallCount++;
                }else if(ch>='0'&&ch<='9') {
                    numberCount++;
                }else {
                    System.out.println("该字符"+ch+"非法");
                }
            }
          //输出结果
            System.out.println("大写字符:"+bigCount+"个");
            System.out.println("小写字符:"+smallCount+"个");
            System.out.println("数字字符:"+numberCount+"个");
        }
    }

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄