Search code examples
c#data-masking

How to mask string after first character


Let's say I have a string that consists of a person's name:

var name = "Jason, Bruno Mars";

How do I mask the string with X for the name behind the comma and returns:

var name = "Jason, BXXXX MXXX";

I have tried using the following methods but only front characters are masked:

string first, second, output;
bool hasSpace, hasComma;
int int_LENGTH;
var name = "Jason, Bruno Mars";
hasComma = name.Contains(",");

if (hasComma == true)
{
    int_LENGTH = name.IndexOf(",");
    if (int_LENGTH > 0)
    {
        first = name.Substring(0, int_LENGTH);
    }

    second = string.Join(",", name.Split(" ").Skip(1));
    hasSpace = second.Contains(" ");

    if (hasSpace == true)
    {
        second = string.Concat(new string('X', 12), second.Substring(second.Length - 4));
        output = first + "," + second;
    }
}

Anyone has a better idea of how can I achieve the same result in a more efficient way?


Solution

  • Another option, using Regex.Matches to select the name parts except the first letter. The regex collects all string parts separated by a space, skipping what's before the comma.
    The collections of Matches is then passed to Linq's Aggregate() method to perform the substitution.
    A StringBuilder is used to store the strings generated by its own Replace() method:

    string theName = "Jason Et Alt., Bruno Mars And More Names";
    var matches = Regex.Matches(theName, @"(?!.*?,)\s+?.(\w+)");
    
    string outName = matches.OfType<Match>().Aggregate(new StringBuilder(theName), (sb, m) => 
       sb.Replace(m.Groups[1].Value, new string('X', m.Groups[1].Length))).ToString();
    

    outname = Jason Et Alt., BXXXX MXXX AXX MXXX NXXXX