public class CalCharNumbers {
public static void main(String[] args) {
System.out.println("请输入一个字符串:");
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();//这里必须要用sc.nextLine();在Java中输入字符串还可以用sc.next();但是这种方式读到空格就会停止
int alphaNum = 0;
int spaceNum = 0;
int digtNum = 0;
int otherNum = 0;
for(int i=0;i<str.length();i++){
if(str.charAt(i)>='0'&&str.charAt(i)<='9'){
digtNum++;
}else if((str.charAt(i)>='a'&&str.charAt(i)<='z')||(str.charAt(i)>='A'&&str.charAt(i)<='Z')){
alphaNum++;
}else if(str.charAt(i)==' '){
spaceNum++;
}else{
otherNum++;
}
}
System.out.println("字母:"+alphaNum+",数字:"+digtNum+",空格:"+spaceNum+",其他字符:"+otherNum);
}
}
用正则表达式实现如下:
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
// 统计一个字符串中字母、空格、数字和其他字符的个数
public class CalCharNumbers {
public static void main(String[] args) {
System.out.println("请输入一个字符串:");
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
String regex1 = "[a-z|A-Z]";
String regex2 = "[0-9]";
CalCharNumbers c = new CalCharNumbers();
int a1 = c.string(s, regex1);
System.out.println("数字的个数:"+a1);
int a2 = c.string(s, regex2);
System.out.println("字母的个数:"+a2);
int a3 = c.string(s, " ");
System.out.println("空格的个数:"+a3);
int a4 = s.length()-a1-a2-a3;
System.out.println("其他字符的个数:"+a4);
}
public int string(String s, String pattern){
Pattern p = Pattern.compile(pattern);//将给定的正则表达式编译到模式中。
Matcher m = p.matcher(s);//创建匹配给定输入与此模式的匹配器。
int i = 0;
while (m.find()) {//尝试查找与该模式匹配的输入序列的下一个子序列。
i++;
}
return i;
}
}