【问题标题】:Replace a Name with String of asterisk at charAt() to a given char but don't replace all of asterisk but only at the position where it matches [duplicate]将 charAt() 处的星号字符串替换为给定字符,但不要替换所有星号,而仅在匹配的位置替换星号 [重复]
【发布时间】:2018-09-10 09:07:45
【问题描述】:
public class Main {

    public static void main(String[] args) throws Exception {
        String name = "eric";
        String nameForYou = name.replaceAll(".","*");
        String afterGuess="";
        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))){
               afterGuess = nameForYou.replace(nameForYou.charAt(i),yourguess.charAt(0));
            }
        }
        System.out.println(afterGuess);
    }
}

我想输出为:

Guess my name: **** 4
***c

我不希望它替换所有的“*”

【问题讨论】:

    标签: java


    【解决方案1】:

    您的策略不起作用,因为replace 替换了它找到的第一个字符,这不一定是正确位置的字符。

    由于 Java String 是不可变的,替换代码的更好方法应该是创建一个适当长度的 char 数组,并将其转换为 String 仅用于打印:

    String name = "eric";
    char[] nameForYou = name.replaceAll(".","*").toCharArray();
    System.out.println("Guess my name: "+new String(nameForYou)+" "+name.length());
    String yourguess = "c";
    for (int i=0;i<name.length();i++) {
        if ((yourguess.charAt(0) == name.charAt(i))){
            nameForYou[i] = yourguess.charAt(0);
        }
    }
    System.out.println(new String(nameForYou));
    

    Java 数组是可变的,因此您可以直接控制特定索引处的字符。如果您不想直接处理数组,也可以使用StringBuilder

    【讨论】:

      猜你喜欢
      • 2013-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-07
      • 1970-01-01
      • 2011-11-11
      相关资源
      最近更新 更多