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

Java实现用数组中两个单词替换单个$字符的方法问询

解决字符串中$替换为数组连续两单词并循环的问题

需求说明

  • 目标数组:{"PUMPKIN", "BAT", "WITCH", "VAMPIRE"}
  • 需将字符串中的每个$替换为数组内连续的两个单词,数组遍历完毕后从头循环
  • 示例:原字符串C$$$$Y(4个$),按逻辑应输出CPUMPKINBATWITCHVAMPIREPUMPKINBATWITCHVAMPIREY;若为3个$则输出CPUMPKINBATWITCHVAMPIREPUMPKINBATY

原代码问题

  1. 当索引ii走到数组最后一位时,ii+1会超出数组下标范围,直接抛出数组越界异常
  2. 索引更新逻辑错误,无法实现数组循环取元素的需求

修正后的代码

public static String stickers(String data) {
    String strg = data;
    // 假设stickers是全局定义或方法传入的数组,此处显式写出方便测试
    String[] stickers = {"PUMPKIN", "BAT", "WITCH", "VAMPIRE"};
    int stickerLength = stickers.length;
    // 统计字符串中$的数量
    int dollarCount = strg.replaceAll("[^$]", "").length();
    int currentIdx = 0;

    for (int i = 0; i < dollarCount; i++) {
        // 计算下一个元素的索引,用取模避免越界
        int nextIdx = (currentIdx + 1) % stickerLength;
        // 拼接要替换的两个单词
        String replaceStr = stickers[currentIdx] + stickers[nextIdx];
        // 找到第一个$的位置并替换
        int dollarPos = strg.indexOf("$");
        strg = strg.substring(0, dollarPos) + replaceStr + strg.substring(dollarPos + 1);
        // 索引前进2位,取模实现循环
        currentIdx = (currentIdx + 2) % stickerLength;
    }

    return strg;
}

代码关键点说明

  • 用(currentIdx + 1) % stickerLength确保下一个元素索引不会越界,比如当currentIdx为3(数组最后一位)时,(3+1)%4=0,自动回到数组第一个元素
  • 每次替换后,将索引currentIdx加2再取模数组长度,保证遍历完数组后从头循环
  • 每次替换都定位字符串中第一个$的位置,逐步完成所有替换

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 08:55:25