Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Masking all characters of a string except for the last n characters

Tags:

string

c#

I want to know how can I replace a character of a string with condition of "except last number characters"?

Example:

string = "4111111111111111";

And I want to make it that

new_string = "XXXXXXXXXXXXX1111"

In this example I replace the character to "X" except the last 4 characters.

How can I possibly achieve this?

like image 587
cheol.lui Avatar asked Mar 07 '13 02:03

cheol.lui


2 Answers

Would that suit you?

var input = "4111111111111111";
var length = input.Length;
var result = new String('X', length - 4) + input.Substring(length - 4);

Console.WriteLine(result);

// Ouput: XXXXXXXXXXXX1111
like image 179
Xavier Poinas Avatar answered Oct 05 '22 09:10

Xavier Poinas


How about something like...

new_string = new String('X', YourString.Length - 4)
                  + YourString.Substring(YourString.Length - 4);

create a new string based on the length of the current string -4 and just have it all "X"s. Then add on the last 4 characters of the original string

like image 34
DRapp Avatar answered Oct 05 '22 11:10

DRapp