Java – What is the best way to mask strings in Java?

What is the best way to mask strings in Java?… here is a solution to the problem.

What is the best way to mask strings in Java?

I

want to apply a mask on the string “96506550”, but I get 965065-50 instead of 96506-550

//my method
public String format(String data, String mask) {
        MaskFormatter mf = new MaskFormatter(mask);        
        return mf.valueToString(data);
}

System.out.println(formatter.format("96506550","#####-###"));

Solution

You forgot to use

public void setPlaceholderCharacter(char placeholder)

This function sets the characters used in place of characters that do not exist in the value, that is, the user must fill them in. The default value is whitespace. This only applies if a placeholder string is not specified or the mask is not fully filled.

This is why the single character placeholder error occurs.

Related Problems and Solutions