这里采用的方法是,先定义一个数字,字符串,特殊字符的字符串标准库,在将标准库转化为字符数组,遍历比较并用计数器统计数字
废话不多说,直接贴代码,各位大佬有什么好的办法也可以在下面留言!!!!
import java.util.Scanner;
/**
* 输入一个字符串,分别统计数字,字母,特殊字符的数量,并打印出来
*/
public class Demo1 {
Scanner sc = new Scanner(System.in);
String inputString = sc.next();
//将控制台输入的字符串转化为Char类型的数组,方便在后面的方法中遍历并使用
char input[] = inputString.toCharArray();
public static void main(String[] args) {
System.out.println("请输入字符串");
Demo1 demo1 = new Demo1();
demo1.countNumber();
demo1.countLetter();
demo1.countSpealSymbol();
}
//统计特殊字符的数量
public void countSpealSymbol() {
int charsetLength = 0;
String charset = "!`~':_-+=/*-+./?~`,<>{}[]()@#$%^&《》?、·……";
//将String类型的字符串转化为Char类型的数组
char chars[] = charset.toCharArray();
for (int z = 0; z < charset.length(); z++) {
for (int j = 0; j < inputString.length(); j++) {
if (input[j] == chars[z]) {
charsetLength++;
}
}
}
System.out.println("特殊字符的数量" + charsetLength);
}
//统计字母的个数
public void countLetter() {
String string = "abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ";
char str[] = string.toCharArray();
int strLength = 0;
for (int i = 0; i < string.length(); i++) {
for (int j = 0; j < inputString.length(); j++) {
if (input[j] == str[i]) {
strLength++;
}
}
}
System.out.println("大小写字母的数量" + strLength);
}
//统计数字的个数
public void countNumber() {
String number = "123456789";
char num[] = number.toCharArray();
int numLength = 0;
for (int z = 0; z < number.length(); z++) {
for (int j = 0; j < inputString.length(); j++) {
if (input[j] == num[z]) {
numLength++;
}
}
}
System.out.println("数字的数量" + numLength);
}
}
下面是测试结果: