Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to i mask all string characters except for the last 4 characters in Java using parameters?

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

like image 992
BinQuan Avatar asked Dec 11 '22 01:12

BinQuan


2 Answers

Solution 1

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.


Solution 2

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.


Solution 3

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);
}
like image 99
Andreas Avatar answered Dec 21 '22 23:12

Andreas


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)
like image 27
Liridon Sadiku Avatar answered Dec 21 '22 23:12

Liridon Sadiku