You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中不使用HashMap统计重复字符(仅用String/StringBuffer)

Fixing Duplicate Character Counting with Only String/StringBuffer in Java

Hey there! I see you're struggling with duplicate counting when tallying repeated characters in a string using only Java's String or StringBuffer—no extra data structures allowed. Let's fix that issue where the same character gets counted over and over (like seeing multiple lines for 'l' with increasing counts when you input multiple "Hello"s).

The Core Idea

The problem with your original code is that it doesn't mark characters as "already counted", so it keeps reprocessing the same character every time it loops. The fix is simple: once we count a character, we remove all instances of it from the string we're processing. This way, each character is only analyzed once, eliminating duplicate output lines.

Working Code

Here's the corrected implementation with clear comments:

import java.util.Scanner;

public class CharCounter {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("输入字符串:");
        String input = scanner.nextLine();
        scanner.close();

        // Use StringBuffer for mutable string operations (since String is immutable)
        StringBuffer workingString = new StringBuffer(input);

        // Keep processing until we've checked all unique characters
        while (workingString.length() > 0) {
            // Pick the first character as our target to count
            char currentChar = workingString.charAt(0);
            int count = 0;

            // Count all occurrences of the target character
            for (int i = 0; i < workingString.length(); i++) {
                if (workingString.charAt(i) == currentChar) {
                    count++;
                }
            }

            // Print the result once per unique character
            System.out.println(currentChar + " : " + count);

            // Remove ALL instances of the counted character to avoid reprocessing
            int charIndex;
            while ((charIndex = workingString.indexOf(String.valueOf(currentChar))) != -1) {
                workingString.deleteCharAt(charIndex);
            }
        }
    }
}

How It Works

  • Mutable String Handling: We use StringBuffer because it lets us modify the string in place (unlike String, which creates a new object every time you change it).
  • Single Pass per Character: For each iteration, we take the first character in the remaining string, count all its occurrences, then delete every instance of that character from the working string.
  • No Duplicate Output: Since we remove the character after counting, it never comes up again in the loop—so each unique character only gets one output line.

Test Example

If you input Hello Hello Hello Hello, the output will be:

H : 4
e : 4
l : 8
o : 4

No more repeated lines for 'l' or 'o'—just a single, accurate count for each unique character.

内容的提问来源于stack exchange,提问作者Arun HC

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:27:49