Java案例怎么统计字符出现次数?

wen java案例 9

本文目录导读:

Java案例怎么统计字符出现次数?

  1. 使用HashMap统计(最常用)
  2. 使用字符串方法(简单场景)
  3. 使用Java 8 Stream API(函数式风格)
  4. 统计特定字符(忽略大小写)
  5. 完整示例:用户输入统计
  6. 性能优化版本(处理大字符串)
  7. 总结建议

在Java中统计字符出现次数有多种实现方式,我来介绍几种常见的方法。

使用HashMap统计(最常用)

import java.util.HashMap;
import java.util.Map;
public class CharCountExample {
    public static void main(String[] args) {
        String str = "hello world hello java";
        Map<Character, Integer> charCount = new HashMap<>();
        // 统计每个字符出现的次数
        for (char c : str.toCharArray()) {
            // 方法1:使用getOrDefault
            charCount.put(c, charCount.getOrDefault(c, 0) + 1);
        }
        // 输出结果
        System.out.println("字符统计结果:");
        for (Map.Entry<Character, Integer> entry : charCount.entrySet()) {
            System.out.println("'" + entry.getKey() + "' : " + entry.getValue() + "次");
        }
    }
}

使用字符串方法(简单场景)

public class CharCountSimple {
    public static void main(String[] args) {
        String str = "hello world";
        char target = 'l';
        // 使用replace方法
        int count = str.length() - str.replace(String.valueOf(target), "").length();
        System.out.println("字符 '" + target + "' 出现了 " + count + " 次");
        // 或者使用charAt循环
        int count2 = 0;
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == target) {
                count2++;
            }
        }
        System.out.println("字符 '" + target + "' 出现了 " + count2 + " 次");
    }
}

使用Java 8 Stream API(函数式风格)

import java.util.Map;
import java.util.stream.Collectors;
public class CharCountStream {
    public static void main(String[] args) {
        String str = "hello world hello java";
        // 使用Stream统计
        Map<Character, Long> charCount = str.chars()
            .mapToObj(c -> (char) c)
            .collect(Collectors.groupingBy(
                c -> c, 
                Collectors.counting()
            ));
        // 输出结果(按出现次数降序排列)
        charCount.entrySet().stream()
            .sorted(Map.Entry.<Character, Long>comparingByValue().reversed())
            .forEach(entry -> 
                System.out.println("'" + entry.getKey() + "' : " + entry.getValue() + "次")
            );
    }
}

统计特定字符(忽略大小写)

public class CaseInsensitiveCount {
    public static void main(String[] args) {
        String str = "Hello Hello HeLLo";
        char target = 'h';
        // 忽略大小写统计
        long count = str.toLowerCase()
                        .chars()
                        .filter(c -> c == Character.toLowerCase(target))
                        .count();
        System.out.println("字符 '" + target + "' (忽略大小写) 出现了 " + count + " 次");
    }
}

完整示例:用户输入统计

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class UserInputCharCount {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要统计的字符串:");
        String input = scanner.nextLine();
        System.out.println("请选择统计方式:");
        System.out.println("1. 统计所有字符");
        System.out.println("2. 统计特定字符");
        int choice = scanner.nextInt();
        if (choice == 1) {
            // 统计所有字符
            Map<Character, Integer> charCount = new HashMap<>();
            for (char c : input.toCharArray()) {
                if (c != ' ') {  // 忽略空格
                    charCount.put(c, charCount.getOrDefault(c, 0) + 1);
                }
            }
            System.out.println("\n字符统计结果(忽略空格):");
            charCount.forEach((key, value) -> 
                System.out.println("'" + key + "' : " + value + "次")
            );
        } else if (choice == 2) {
            // 统计特定字符
            System.out.println("请输入要统计的字符:");
            char target = scanner.next().charAt(0);
            long count = input.chars()
                             .filter(c -> c == target)
                             .count();
            System.out.println("字符 '" + target + "' 出现了 " + count + " 次");
        }
        scanner.close();
    }
}

性能优化版本(处理大字符串)

import java.util.HashMap;
import java.util.Map;
public class EfficientCharCount {
    public static Map<Character, Integer> countChars(String str) {
        Map<Character, Integer> result = new HashMap<>();
        // 预先设置容量,减少重新哈希
        int initialCapacity = (int) (str.length() / 0.75f) + 1;
        result = new HashMap<>(initialCapacity);
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            Integer count = result.get(c);
            if (count == null) {
                result.put(c, 1);
            } else {
                result.put(c, count + 1);
            }
        }
        return result;
    }
    public static void main(String[] args) {
        String text = "This is a long text with many characters...";
        Map<Character, Integer> counts = countChars(text);
        // 找到出现次数最多的字符
        Map.Entry<Character, Integer> maxEntry = null;
        for (Map.Entry<Character, Integer> entry : counts.entrySet()) {
            if (maxEntry == null || entry.getValue() > maxEntry.getValue()) {
                maxEntry = entry;
            }
        }
        if (maxEntry != null) {
            System.out.println("出现最多的字符: '" + maxEntry.getKey() 
                             + "' 出现 " + maxEntry.getValue() + " 次");
        }
    }
}

总结建议

  1. 简单统计:使用 HashMapString.replace() 方法
  2. 函数式编程:使用 Java 8 Stream API
  3. 性能要求:使用 charAt() 循环 + 预分配 Map 容量
  4. 特殊需求:忽略大小写、只统计字母数字等

选择哪种方法取决于你的具体需求场景,对于大多数情况,使用 HashMap 统计就足够了。

抱歉,评论功能暂时关闭!