It may be a bit of Overkill at your request. But here is a quick extension method that does this.
x is used by default as a masking Char, but it can be changed with an extra character
public static class Masking { public static string MaskAllButLast(this string input, int charsToDisplay, char maskingChar = 'x') { int charsToMask = input.Length - charsToDisplay; return charsToMask > 0 ? $"{new string(maskingChar, charsToMask)}{input.Substring(charsToMask)}" : input; } }
Here are unit tests to prove it works.
using Xunit; namespace Tests { public class MaskingTest { [Theory] [InlineData("ThisIsATest", 4, 'x', "xxxxxxxTest")] [InlineData("Test", 4, null, "Test")] [InlineData("ThisIsATest", 4, '*', "*******Test")] [InlineData("Test", 16, 'x', "Test")] [InlineData("Test", 0, 'y', "yyyy")] public void Testing_Masking(string input, int charToDisplay, char maskingChar, string expected) {
Wizardhammer
source share