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

如何统计字符串字符出现次数并按索引替换为对应出现次数

通用Java实现:将指定字符替换为累计出现次数

需求说明

统计字符串中指定字符的出现次数,并将该字符替换为到其所在索引位置为止的累计出现次数。例如处理字符串"hello"、指定字符为'l'时,期望输出结果为"he12o"。

实现方案

下面是具备复用性的通用实现,通过工具方法封装逻辑,支持任意输入字符串和目标字符:

public class StringCharReplacer {
    // 核心方法:将输入字符串中的目标字符替换为累计出现次数
    public static String replaceTargetCharWithCount(String inputStr, char target) {
        StringBuilder resultBuilder = new StringBuilder();
        int occurrenceCount = 0;

        // 遍历字符串每个字符
        for (char currentChar : inputStr.toCharArray()) {
            if (currentChar == target) {
                occurrenceCount++;
                // 将累计次数转为字符串追加到结果中
                resultBuilder.append(occurrenceCount);
            } else {
                // 非目标字符直接保留
                resultBuilder.append(currentChar);
            }
        }

        return resultBuilder.toString();
    }

    // 测试示例
    public static void main(String[] args) {
        String testStr = "hello";
        char targetChar = 'l';
        String output = replaceTargetCharWithCount(testStr, targetChar);
        System.out.println(output); // 输出:he12o

        // 扩展测试:处理多次出现的情况
        String anotherTest = "llllllllll";
        String anotherOutput = replaceTargetCharWithCount(anotherTest, 'l');
        System.out.println(anotherOutput); // 输出:12345678910
    }
}

代码说明

  • 使用StringBuilder进行字符串拼接,相比直接+拼接字符串,避免了频繁创建字符串对象的性能开销
  • 维护一个计数器occurrenceCount,每遇到一次目标字符就递增,确保替换的是到当前位置的累计次数
  • 方法参数支持任意输入字符串和目标字符,具备完全的复用性,可直接在其他场景调用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 22:25:42