Mask String with characters

Is this for making a password? Consider the following:

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();
    }
}

Or for the hangman approach

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();
    }
}

Just create a string with the same number of characters as your original, with instead your "obfuscating" character.

String x = "ABCD";

String output = "";
for (int i = 0; i < x.length(); i++) {
    output += "*";
}

Alternatively you could use x.replaceAll("\\S", "*"), which would preserve whitespace as well.


There are several ways to achieve this, it would depend on your application.

If you want to mask all characters with another character in one fell swoop you can use the String#replaceAll(String regex, String replacement) method: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replaceAll(java.lang.String,%20java.lang.String).

This involves using Regular Expressions, for regex you would use [\s\S] which will match any whitespace or non whitespace character. For replacement you use a regular string, not a RegEx. In this case, if you wanted an asterisk, use "*", for hyphen "-", very simple.

All the other methods here work well except the @Roddy of the Frozen Pea and @djc391 ones, so that's why I answered it correctly.

Good luck

Tags:

Java