- import java.util.Scanner;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- public class Test2 {
- /**
- * 从键盘录入一个字符串实现:
- * 1.大写字母字符,小写字母字符,数字字符出现的次数,其他字符出现的次数,
- * 2.分别输出大写字母 小写字符 数字 其他字符。
- *
- * getCount()方法实现
- * 定义统计变量,遍历该字符串,判断是否为相应的数据,如果是,则相应的统计变量加1,
- * 输出最后的统计变量值
- *
- * splitString()方法实现
- * 按照正则表达式进行匹配,如果匹配成功就输出来.
- *
- * splitStringResult(line)
- * 格式化输出所要的信息
- */
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- System.out.println("请输入一个字符串:");
- String line = sc.nextLine();
-
- getCount(line);
-
- splitStringResult(line);
- }
- private static void splitStringResult(String line) {
- String regex = "[A-Z]";
- String regex1 = "[a-z]";
- String regex2 = "\\d";
- String regex3 = "[^a-zA-Z^0-9]";
-
- System.out.print("大写字母为:");
- splitString(line, regex);
- System.out.println();
-
- System.out.print("小写字母为:");
- splitString(line, regex1);
- System.out.println();
-
- System.out.print("数字字母为:");
- splitString(line, regex2);
- System.out.println();
-
- System.out.print("其他字母为:");
- splitString(line, regex3);
- }
- private static void splitString(String line, String regex) {
- Pattern p = Pattern.compile(regex);
- Matcher m = p.matcher(line);
-
- while(m.find()) {
- System.out.print(m.group());
- }
- }
- private static void getCount(String line) {
- char[] arr = line.toCharArray();
-
- int bigChar = 0;
- int smallChar = 0;
- int number = 0;
- int otherChar = 0;
- for (int i = 0; i < arr.length; i++) {
- if(arr[i] >= 'A' && arr[i] <= 'Z') {
- bigChar++;
- }else if(arr[i] >= 'a' && arr[i] <='z') {
- smallChar++;
- }else if(arr[i] >= '0' && arr[i] <= '9') {
- number++;
- }else {
- otherChar++;
- }
- }
-
- System.out.println("大写字母个数为:" + bigChar);
- System.out.println("小写字母个数为:" + smallChar);
- System.out.println("数字字母个数为:" + number);
- System.out.println("其他字母个数为:" + otherChar);
- }
- }
复制代码
|
|