首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 統計字符串中字符出現次數(僅限小寫字母)

     編輯:Java 相關知識

需求

給定一個字符串,統計其中每個小寫字母(a-z)出現的次數並輸出。

核心代碼

package com;

import org.junit.Test;

public class StringTest {
    @Test
    public void test() {
        String s = "fdfaacceeeeeeeeeeeegghikkkkkoooo";
        count(s);
    }

    public static void count(String str) {
        int[] freq = new int[26]; // a-z 對應 0-25

        for (char ch : str.toCharArray()) {
            if (ch >= 'a' && ch <= 'z') {
                freq[ch - 'a']++;
            }
        }

        for (int i = 0; i < freq.length; i++) {
            if (freq[i] > 0) {
                System.out.println((char)('a' + i) + " : " + freq[i]);
            }
        }
    }
}

運行輸出

a : 3
c : 2
d : 1
e : 12
f : 2
g : 2
h : 1
i : 1
k : 5
o : 4

擴展:統計所有可見字符

public static void countAll(String str) {
    Map<Character, Integer> map = new HashMap<>();
    for (char ch : str.toCharArray()) {
        map.merge(ch, 1, Integer::sum);
    }
    map.entrySet().stream()
        .sorted(Map.Entry.comparingByKey())
        .forEach(e -> System.out.println(e.getKey() + " : " + e.getValue()));
}

Java 8 Stream 一行寫法

str.chars()
   .filter(c -> c >= 'a' && c <= 'z')
   .mapToObj(c -> (char) c)
   .collect(Collectors.groupingBy(c -> c, Collectors.counting()))
   .entrySet().stream()
   .sorted(Map.Entry.comparingByKey())
   .forEach(e -> System.out.println(e.getKey() + " : " + e.getValue()));

總結

利用 int[26] 數組映射 a-z 索引是最高效的定制方案;通用字符統計推薦 Map 或 Stream API。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved