掩码字符串

Jau*_*oyd 7 java

嘿家伙我试图找到隐藏字符串的方法,但我发现的代码只适用于我的应用程序...有没有办法用"*"或" - "隐藏字符串中的字符,如果有的话是有人可以请解释

cor*_*iKa 8

这是用于制作密码吗?考虑以下:

class Password {
    final String password; // the string to mask
    Password(String password) { this.password = password; } // needs null protection
    // allow this to be equal to any string
    // reconsider this approach if adding it to a map or something?
    public boolean equals(Object o) {
        return password.equals(o);
    }
    // we don't need anything special that the string doesnt
    public int hashCode() { return password.hashCode(); }
    // send stars if anyone asks to see the string - consider sending just
    // "******" instead of the length, that way you don't reveal the password's length
    // which might be protected information
    public String toString() {
        StringBuilder sb = new StringBuilder();
        for(int i = 0; < password.length(); i++) 
            sb.append("*");
        return sb.toString();
    }
}
Run Code Online (Sandbox Code Playgroud)

或者对于刽子手的方法

class Hangman {
    final String word;
    final BitSet revealed;
    public Hangman(String word) {
        this.word = word;
        this.revealed = new BitSet(word.length());
        reveal(' ');
        reveal('-');
    }
    public void reveal(char c) {
        for(int i = 0; i < word.length; i++) {
            if(word.charAt(i) == c) revealed.set(i);
        }
    }
    public boolean solve(String guess) {
        return word.equals(guess);
    }
    public String toString() {
         StringBuilder sb = new StringBuilder(word.length());
         for(int i = 0; i < word.length; i++) {
             char c = revealed.isSet(i) ? word.charAt(i) : "*";
         }
         return sb.toString();
    }
}
Run Code Online (Sandbox Code Playgroud)


Rod*_*eas 5

只需使用与原始字符数相同的字符数创建一个字符串,即可使用“混淆”字符。

String x = "ABCD";

String output = "";
for (int i = 0; i < x.length(); i++) {
    output += "*";
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用x.replaceAll("\\S", "*"),它也会保留空白。

  • 只有自从OP说“有没有办法用“**”*或“-”隐藏字符串中的字符以来,英语已经发生了显着变化?”。for 循环遍历字符串并将每个字符替换为“*”。 (2认同)