i will like to know how do i mask any number of string characters except the last 4 strings. I want to masked all strings using "X"
For example
Number:"S1234567B"
Result
Number :"XXXXX567B
Thank you guys
You can do it with a regular expression.
This is the shortest solution.
static String mask(String input) {
return input.replaceAll(".(?=.{4})", "X");
}
The regex matches any single character (.
) that is followed (zero-width positive lookahead) by at least 4 characters ((?=.{4})
). Replace each such single character with an X
.
You can do it by getting a char[]
1, updating it, and building a new string.
This is the fastest solution, and uses the least amount of memory.
static String mask(String input) {
if (input.length() <= 4)
return input; // Nothing to mask
char[] buf = input.toCharArray();
Arrays.fill(buf, 0, buf.length - 4, 'X');
return new String(buf);
}
1) Better than using a StringBuilder
.
You can do it using the repeat(int count)
method that was added to String
in Java 11.
This is likely the easiest solution to understand.
static String mask(String input) {
int maskLen = input.length() - 4;
if (maskLen <= 0)
return input; // Nothing to mask
return "X".repeat(maskLen) + input.substring(maskLen);
}
Kotlin extension which will take care of the number of stars that you want to set and also number of digits for ex: you have this string to be masked: "12345678912345" and want to be ****2345 then you will have:
fun String.maskStringWithStars(numberOfStars: Int, numberOfDigitsToBeShown: Int): String {
var stars = ""
for (i in 1..numberOfStars) {
stars += "*"
}
return if (this.length > numberOfDigitsToBeShown) {
val lastDigits = this.takeLast(numberOfDigitsToBeShown)
"$stars$lastDigits"
} else {
stars
}
}
Usage:
companion object{
const val DEFAULT_NUMBER_OF_STARS = 4
const val DEFAULT_NUMBER_OF_DIGITS_TO_BE_SHOWN = 4
}
yourString.maskStringWithStars(DEFAULT_NUMBER_OF_STARS,DEFAULT_NUMBER_OF_DIGITS_TO_BE_SHOWN)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With