問題 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();
        
    }

}
 

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