BinQuan
BinQuan

Reputation: 95

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

Upvotes: 8

Views: 23415

Answers (5)

Liridon Sadiku
Liridon Sadiku

Reputation: 349

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)

Upvotes: 1

Linh
Linh

Reputation: 60923

My class to mask simple String

class MaskFormatter(private val pattern: String, private val splitter: Char? = null) {

    fun format(text: String): String {
        val patternArr = pattern.toCharArray()
        val textArr = text.toCharArray()
        var textI = 0
        for (patternI in patternArr.indices) {
            if (patternArr[patternI] == splitter) {
                continue
            }
            if (patternArr[patternI] == 'A' && textI < textArr.size) {
                patternArr[patternI] = textArr[textI]
            }
            textI++
        }
        return String(patternArr)
    }
}

Example use

MaskFormatter("XXXXXAAAA").format("S1234567B") // XXXXX567B
MaskFormatter("XX.XXX.AAAA", '.').format("S1234567B") // XX.XXX.567B
MaskFormatter("**.***.AAAA", '.').format("S1234567B") // **.***.567B
MaskFormatter("AA-AAA-AAAA",'-').format("123456789") // 12-345-6789

Upvotes: 0

Andreas
Andreas

Reputation: 159114

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

Upvotes: 24

823
823

Reputation: 73

You can do it with the help of StringBuilder in java as follows,

String value = "S1234567B";
String formattedString = new StringBuilder(value)
    .replace(0, value.length() - 4, new String(new char[value.length() - 4]).replace("\0", "x")).toString();
System.out.println(formattedString);

Upvotes: 0

Sweeper
Sweeper

Reputation: 271775

You can use a StringBuilder.

StringBuilder sb = new StringBuilder("S1234567B");
for (int i = 0 ; i < sb.length() - 4 ; i++) { // note the upper limit of the for loop
    // sets every character to X until the fourth to last character
    sb.setCharAt(i, 'X');
}
String result = sb.toString();

Upvotes: 0

Related Questions