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

Java实现猜名字功能:仅替换匹配位置的星号为指定字符

修复猜名字代码的精准字符替换问题

我来帮你搞定这个猜名字的代码问题~

原代码里的核心问题是:当你用replace方法替换字符时,因为nameForYou全是*,它会把所有星号都换成你猜测的字符,而不是只替换原名字中匹配的那个位置。比如你猜"c",原代码会输出cccc而不是期望的***c。

修正后的代码

我们可以用StringBuilder来逐个构建结果,精准控制只替换对应位置的字符:

public class Main { 
    public static void main(String[] args) throws Exception { 
        String name = "eric"; 
        // 初始化与原名字长度一致的星号字符串
        StringBuilder nameForYou = new StringBuilder();
        for (int i = 0; i < name.length(); i++) {
            nameForYou.append('*');
        }
        System.out.println("Guess my name: " + nameForYou + " " + name.length()); 
        
        String yourguess = "c"; 
        // 遍历原名字的每个字符,匹配则替换对应位置的星号
        for (int i = 0; i < name.length(); i++) { 
            if (yourguess.charAt(0) == name.charAt(i)) {
                nameForYou.setCharAt(i, yourguess.charAt(0));
            } 
        } 
        System.out.println(nameForYou); 
    } 
}

关键修正点

  • 用StringBuilder初始化星号字符串,支持直接修改指定索引的字符
  • 匹配到猜测字符时,使用setCharAt(i, 目标字符)只替换对应位置的星号,不会影响其他位置
  • 运行后就能得到你期望的输出:
    Guess my name: **** 4
    ***c
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:29:48