问题 D: C语言-字符统计2

问题 D: C语言-字符统计2

时间限制: 1 Sec  内存限制: 128 MB
提交: 1255  解决: 646
[提交] [状态] [命题人:外部导入]

题目描述

编写一函数,由实参传来一个字符串,统计此字符串中字母、数字、空格和其它字符的个数,在主函数中输入字符串以及输出上述结果。 只要结果,别输出什么提示信息。

输入

一行字符串

输出

统计数据,4个数字,空格分开。

样例输入 Copy

!@#$%^QWERT    1234567

样例输出 Copy

5 7 4 6 

解法1:正则匹配,优化之后的。需要注意的是,java里面的特殊符号匹配用的是双反斜杠。

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        // TODO 自动生成的方法存根
        Scanner scan = new Scanner(System.in);
        //int n = scan.nextInt();
        String temp = scan.nextLine();
        //StringBuffer out = new StringBuffer();
        int[] count = new int[4];
        for(int i=0;i<temp.length();i++) {
            if((temp.charAt(i)+"").matches("[0-9]{1}")) {
                count[1]++;
            }else if((temp.charAt(i)+"").matches("[a-zA-Z]{1}")) {
                count[0]++;
            }else if((temp.charAt(i)+"").matches("\\s{1}")) {
                count[2]++;
            }else {
                count[3]++;
            }
        }
        for(int i=0;i<3;i++) {
            System.out.print(count[i]+" ");
        }
        System.out.println(count[3]);
    }

}
解法2:我最开始的解法,算法思维相同,不同的是,判断条件写起来很繁琐。

import java.util.Scanner;


public class Main {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner scan = new Scanner(System.in);
        String str = scan.nextLine();
        int[] ct = new int[1001];
        for(int i=0;i<str.length();i++){
            if(('a'<=str.charAt(i)&&str.charAt(i)<='z')||('A'<=str.charAt(i)&&str.charAt(i)<='Z')){
                ct[0]++;
            }else if('0'<=str.charAt(i)&&str.charAt(i)<='9'){
                ct[1]++;
            }else if(str.charAt(i)==' '){
                ct[2]++;
            }else{
                ct[3]++;
            }
        }
        for(int i=0;i<4;i++){
            System.out.printf("%d ", ct[i]);
        }
        System.out.println();
        
    }

}
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章