Java字符串小练习

一.键盘输入一个字符串,并且统计其中各种字符串出现的次数
思路:

  1. 键盘输入,用Scanner
  2. 接收字符串,用String str = sc.next()
  3. 定义四个变量, 分别代表四个字符各自出现的次数
  4. 需要对字符串一个字一个字检查,String–>char[], 方法就是toCharArray()
  5. 遍历char[]字符数组,对当前的字符种类进行判断,用四个变量进行++操作
  6. 打印输出四个变量
public class Demo09StringCount
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个字符串:");
        String input = sc.next(); //接收字符串

        int countUpper = 0;//大写字母出现次数
        int countLower = 0;//小写字母出现次数
        int countNumber = 0; //数字出现次数
        int countOther = 0; //其他字符出现次数

        char[] charArray = input.toCharArray();
        for(int i = 0; i < charArray.length; i++)
        {
            char ch = charArray[i];
            if('A' <= ch &&  'Z' >= ch )
            {
                countUpper++;
            }
            else if('a' <= ch && 'z' >= ch)
            {
                countLower++;
            }
            else if('0' <= ch && '9' >= ch)
            {
                countNumber++;
            }
            else
            {
                countOther++;
            }
        }
        System.out.println("大写字母有: " + countUpper + "个");
        System.out.println("小写字母有: " + countLower + "个");
        System.out.println("数字有: " + countNumber + "个");
        System.out.println("其他字符有: " + countOther + "个");
    }

}

在这里插入图片描述


二. 把数组{1,2,3}按照指定格式拼接成一个字符串 [EVE1#EVE2#PVP3]
思路:

  1. 先准备一个int[]数组,
  2. 定义一个方法,用来将数组变成字符串
    三要素:
    返回值类型 String
    方法名称 fromArrayToString
    参数列表 int[]
  3. 格式 [EVE1#EVE2#PVP3]
  4. 调用方法,得到返回值,并打印结果字符串
public class Demo08StringPractise
{
    public static void main(String[] args)
    {
        int [] arr = {1,2,3};
        String str = fromArrayToString(arr);
        System.out.println(str);
    }
    public static String fromArrayToString (int [] arr)
    {
        String str1 = "["; //开头
        for(int i = 0; i <arr.length; i++)
        {
            if(i == arr.length - 1)
            {
                str1 = str1 + "PVP" + arr[i] + "]"; //尾巴
            }
            else
            {
                str1 = str1 + "EVE" + arr[i] + "#"; //中间
            }

        }
        return str1;
    }
}

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值