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

This might be a little Overkill for your ask. But here is a quick extension method that does this.

it defaults to using x as the masking Char but can be changed with an optional char

   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 a 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)
        {
            //Act
            string actual = input.MaskAllButLast(charToDisplay, maskingChar);

            //Assert
            Assert.Equal(expected, actual);
        }
    }
}

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


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

Here's a way to think through it. Call the last number characters to leave n:

  1. How many characters will be replaced by X? The length of the string minus n.
  2. How can we replace characters with other characters? You can't directly modify a string, but you can build a new one.
  3. How to get the last n characters from the original string? There's a couple ways to do this, but the simplest is probably Substring, which allows us to grab part of a string by specifying the starting point and optionally the ending point.

So it would look something like this (where n is the number of characters to leave from the original, and str is the original string - string can't be the name of your variable because it's a reserved keyword):

// 2. Start with a blank string
var new_string = "";

// 1. Replace first Length - n characters with X
for (var i = 0; i < str.Length - n; i++)
    new_string += "X";

// 3. Add in the last n characters from original string.
new_string += str.Substring(str.Length - n);

Tags:

C#

String