Mask data like XXX XX 8743

If your requirement is to mask some part of the data and show only last few digits then this solution helps you to fix your requirement.

We can do this in a simple way if we knew the number of digits passed are fixed and want to hide fixed number of digits and show fixed number of digits.

eg: You always pass 9 digit number and want to mask first 6 numbers and show last 3 numbers.

String s ="123456789"; //Fixed 9 digit length of number
String mask = "XXXXXX"; //Fixed 6 digit length of number to be masked
s= s.substring(6) + mask; // output: XXXXXX789

Let’s take an example where the number of digits vary and also the number of digits we have to show also vary then the below code will help you.


public static void main(String[] args) {
mask(1234567,2);
}

private static String mask(int maskData, int unmaskCount){
try{
int  masksize_length = (int) (Math.log10(maskData)+1)-unmaskCount;
System.out.println("masksize_length:"+masksize_length);
Integer maskData1 = new  Integer(maskData);
String fixMask = "";
int i =1;
while(i<= masksize_length){
fixMask = fixMask.concat("X");
//System.out.println("fixMask:"+fixMask);
i++;
}
String maskedData = maskData1.toString();
maskedData = fixMask.concat(maskedData.substring(masksize_length));
System.out.println("maskedData:"+maskedData);
return maskedData;
}
catch(Exception e){
}
return null;

}

For the above code if you pass input as

mask(1234567,2); then output would be: XXXXX67
mask(1234567891,4); then output would be: XXXXXX7891
mask(1236432,3); then output would be: XXXX432
If you’ve any doubts or better solution..please leave  your suggestion in the comment section.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s