JAVA经典算法(七)

本文介绍了一个使用Java编写的程序,该程序能够接收用户输入的字符串,并统计其中的大写字母、小写字母、数字、空格和其他字符的数量。通过两种方法实现:一种是利用ASCII码进行判断,另一种是使用Character类的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。

package cn.ls.lanqiao;

import java.util.Scanner;

public class Test7 {
	public static void main(String[] args) {
		int daXie = 0;
		int xiaoXie = 0;
		int kongGe = 0;
		int number = 0;
		int other = 0;
		System.out.println("请输入字符串:");
		Scanner sc = new Scanner(System.in);
		String str = sc.nextLine();
	/*	
	 * 方法一,利用ASCII码去解决
	 * for (int i = 0; i < str.length(); i++) {
			char c = str.charAt(i);
			if (c >= 65 && c <= 90)
				daXie++;
			else if (c >= 97 && c <= 122)
				xiaoXie++;
			else if (c >= 48 && c <= 57)
				number++;
			else if (c == 32)
				kongGe++;
			else
				other++;
		}*/
		//方法二,利用Character的方法去解决,先把字符串转化为char数组
		  char[] ls = str.toCharArray();
	        for(int i=0;i<ls.length;i++){
	            if(Character.isUpperCase(ls[i])){
	            	daXie++;
	            }else if(Character.isLowerCase(ls[i])) {
	            	xiaoXie++;
	            }else if(Character.isDigit(ls[i])){
	            	number++;
	            }else if(Character.isSpaceChar(ls[i])){
	            	kongGe++;
	            }else{
	            	other++;
	            }
	        }

		System.out.println(str + "中大写字母的个数为" + daXie + "个");
		System.out.println(str + "中小写字母的个数为" + xiaoXie + "个");
		System.out.println(str + "中数字的个数为" + number + "个");
		System.out.println(str + "中空格的个数为" + kongGe + "个");
		System.out.println(str + "中其他字符的个数为" + other + "个");
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值