统计各种字符(英文字母、空格、数字和其它字符)的个数

import java.util.*;

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

	public static void main(String[] args) {

		int iSpace = 0, iLetter = 0, iNumber = 0, iElse = 0;
		Scanner sc = new Scanner(System.in);
		String str = sc.nextLine();
		char[] ch = str.toCharArray();
		for (int i = 0; i < ch.length; i++) {
			if (ch[i] == ' ') {
				iSpace++;
			} else if (ch[i] >= 'A' && ch[i] <= 'Z' || ch[i] >= 'a' && ch[i] <= 'z') {
				iLetter++;
			} else if (ch[i] >= 48 && ch[i] <= 57) {	//0~9的ASCII
				iNumber++;
			} else {
				iElse++;
			}
		}
		System.out.println("空格个数:"+iSpace);
		System.out.println("字母个数:"+iLetter);
		System.out.println("数字个数:"+iNumber);
		System.out.println("其他个数:"+iElse);

	}

}

以下是使用 Java 编写的统计输入的一行字符英文字母空格数字其他字符个数的代码: ```java import java.util.Scanner; public class CharacterCount { public static void main(String[] args) { int englishCount = 0; int blankCount = 0; int numberCount = 0; int otherCharacterCount = 0; Scanner sc = new Scanner(System.in); System.out.println("请输入一串字符串"); String s = sc.nextLine(); char[] charArrays = s.toCharArray(); for (int i = 0; i < charArrays.length; i++) { if ((charArrays[i] >= 65 && charArrays[i] <= 90) || (charArrays[i] >= 97 && charArrays[i] <= 122)) { // 判断是否为英文字母, A - Z 65 - 90 a - z 97 - 122 englishCount++; continue; } // 空格的 ascii 码值是 32 if (charArrays[i] == 32) { blankCount++; continue; } // 数字 0~9 对应的 ASCII 码范围为 [48, 57] if ((charArrays[i] >= 48 && charArrays[i] <= 57)) { // 判断是否为数字 numberCount++; continue; } // 当不是英文字母空格数字时, 那么就代表它是其他字符了 otherCharacterCount++; } System.out.println("英文字母个数为:" + englishCount); System.out.println("空格个数为:" + blankCount); System.out.println("数字个数为:" + numberCount); System.out.println("其他字符个数为:" + otherCharacterCount); } } ``` 以上代码参考了统计输入一行字符中各类字符个数的逻辑,通过 `Scanner` 类获取用户输入的字符串,将其转换为字符数组,然后遍历数组,根据 ASCII 码范围判断每个字符的类型并进行相应的计数,最后输出各类字符个数 [^1][^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值