字符個數統計

題目描述

編寫一個函數,計算字符串中含有的不一樣字符的個數。字符在ACSII碼範圍內(0~127)。不在範圍內的不做統計。

輸入描述

輸入N個字符,字符在ACSII碼範圍內(0~127)。

輸出描述

輸出字符的個數。

輸入例子

abc

輸出例子

3

算法實現

import java.util.Scanner;

/**
 * 
 * All Rights Reserved !!!
 */
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            int[] arr = new int[128];
            String input = scanner.nextLine();
            countChar(arr, input);
            System.out.println(countCharNum(arr));
        }

        scanner.close();
    }

    private static void countChar(int[] arr, String input) {
        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            if (c <= 127) {
                arr[c]++;
            }
        }
    }

    private static int countCharNum(int[] arr) {
        int result = 0;
        for (int i : arr) {
            if (i != 0) {
                result++;
            }
        }

        return result;
    }
}
相關文章
相關標籤/搜索