AppeShopper
AppeShopper

Reputation: 265

Masks first name of a string

How effectively mask first name from a string?

Input: Dear Elaine Jasper, Thank you for coming

Output: Dear **** Jasper, Thank you for coming

Input: Dear Muhammad Ali Yusuf, Thank you for coming

Output: Dear **** **** Yusuf, Thank you for coming

Input: Dear Yusuf, Thank you for coming

Output: Dear Yusuf, Thank you for coming

Currently I'm able to removed everything before the comma,

string output1 = input.Substring(input.IndexOf(',') + 1);
string output = "Dear ****," + output1;

But I'm not entirely sure how to make the surname remain.

The message is for logging, client request to mask the first name.

Upvotes: 4

Views: 963

Answers (6)

Fabjan
Fabjan

Reputation: 13676

Well, you could do something along the lines of:

    public static string MaskNames(string input)
    {
        var names = input.Split(new[] { "Dear ", "," }, StringSplitOptions.RemoveEmptyEntries).First().Split(' ').ToList();
        string stringToReplace = names.Any() ? string.Join(" ", names.Take(names.Count - 1)) : null;

        if (!string.IsNullOrEmpty(stringToReplace))
        {
            var maskedNameStr = string.Join(" ", names.Take(names.Count - 1).Select(s => new string('*', s.Length)));
            return input.Replace(stringToReplace, maskedNameStr);
        }
        return input;
    }

And the usage:

MaskNames("Dear Elaine ABC Jasper, Thank you for coming**");
MaskNames("Dear Yusuf, Thank you for coming");

Upvotes: 1

Magnus
Magnus

Reputation: 46947

My contribution:

public string Mask(string sentence)
{
    const string mask = "****";
    var parts = sentence.Split(',');
    var words = parts[0].Split(' ');
    var masked = words.Select((w, i) => i == 0 || i == words.Length - 1 ? w : mask);
    return string.Join(" ", masked) + "," + parts[1];
}

Upvotes: 0

C.RaysOfTheSun
C.RaysOfTheSun

Reputation: 716

The method in the snippet below works by first grabbing the first segment of the input string (the part that is left of the comma) then obtaining the supposed first name from the above-mentioned string (which is between the first and last spaces) then masking it. :)

   public static string MaskFirstName(string greeting)
   {
        // make sure there's something to actually work with
        if(greeting.Trim() == string.Empty)
        {
            return string.Empty;
        }

        string masked = "";

        // clean up the input string by removing any leading and trailing white spaces
        greeting = greeting.Trim();

        // index of the comma
        int commaInd = greeting.IndexOf(',');

        // get the name of the person
        string target = greeting.Substring(0, commaInd);

        // index of the first space
        int firstSpaceInd = target.IndexOf(' ');

        // index of the last space
        int lastSpaceInd = target.LastIndexOf(' ');

        // The indiviual chars of our target string
        char[] chars = target.ToCharArray();

        // replace the characters between the first space and the last space in our target string
        for (int i = firstSpaceInd + 1; i != lastSpaceInd; i++)
        {
            chars[i] = '*';
        }

        // rebuild our original input string with the masked name
        masked = greeting.Replace(target, new string(chars));

        return masked;
    }

The output of the method above will be something like

input: Dear Muhammad Ali Yusuf, Thank you for coming
output: Dear ************ Yusuf, Thank you for coming

input: Dear Elaine Jasper, Thank you for coming
output: Dear ****** Jasper, Thank you for coming

Upvotes: 0

SᴇM
SᴇM

Reputation: 7213

You can use String.Split Method, to split your sentence into two parts, then from first part, which contains the word Dear and your whole name, take only names, mask them, and compose new one.

public string HideName(string str)
{
    //First split by comma
    var splittedByComma = str.Split(',');

    //Then get separate words from splitted array's first part
    var words = splittedByComma[0].Split(' ');

    //Get names before last name
    var name = words.Skip(1).Take(words.Length - 2);

    //Replace all chars from first names with '*'
    var hiddenPart = string.Join(" ", name.Select(s => new string(s.Select(ch => '*').ToArray())));

    //Compose result
    var result = string.Format("Dear {0} {1}, {2}", hiddenPart, words.Last(), splittedByComma[1].Trim());

    return result;
}

Usage:

var strs = new[] 
{ 
    "Dear Elaine Jasper, Thank you for coming", 
    "Dear Muhammad Ali Yusuf, Thank you for coming", 
    "Dear Yusuf, Thank you for coming" 
};

foreach (var item in strs)
{
    var djfdsf = HideName(item);
}

Output:

Dear ****** Jasper, Thank you for coming

Dear ******** *** Yusuf, Thank you for coming

Dear Yusuf, Thank you for coming

References: DotNetFiddle Example, String.Split Method, String.Join method, Enumerable.Select Method, Enumerable.Skip Method, Enumerable.Take Method

Upvotes: 0

Dhanushka Dayawansha
Dhanushka Dayawansha

Reputation: 356

try this

  string phrase = "Dear Muhammad Ali Yusuf, Thank you for coming";

        string[] words_1 = phrase.Split(',');

        string[] words_2=words_1[0].Split(' ');

        string newstr = words_2[0] ;

        for (int i=0;i<words_2.Length;i++)
        {
            if (i>0 && i< words_2.Length-1)
            {
                newstr =newstr+ " ****";
            }

        }


        Console.WriteLine(newstr+" "+words_2[words_2.Length-1] + words_1[1]);

enter image description here

Upvotes: 0

Alex Domenici
Alex Domenici

Reputation: 769

here's a function that should help you. Please note that it can be optimized more for performance, and also note that the function assumes the surname is a single word.

using System;

public class Program
{
    public static void Main()
    {
        Console.WriteLine(MaskName("Dear John Sanders, welcome to our new service."));
        Console.WriteLine(MaskName("Dear John Sanders, welcome to our new service.", true));

        Console.WriteLine(MaskName("Dear John Matthew Sanders, welcome to our new service."));
        Console.WriteLine(MaskName("Dear John Matthew Sanders, welcome to our new service.", true));
    }

    public static string MaskName(string text, bool maskSurname = false)
    {
        var greeting = text.Substring(0, text.IndexOf(','));
        var message = text.Substring(greeting.Length);

        var parts = greeting.Split(' ');

        for (int i = 1; i < parts.Length; i++) // Start from 1, skipping "Dear"
        {
            if (i == parts.Length - 1 && !maskSurname) continue; // Optionally mask the surname
            greeting = greeting.Replace(parts[i], "*****");         
        }

        return greeting + message;
    }
}

Run the program and the output will be:

Dear ***** Sanders, welcome to our new service.
Dear ***** *****, welcome to our new service.
Dear ***** ***** Sanders, welcome to our new service.
Dear ***** ***** *****, welcome to our new service.

Hope that helps :)

Upvotes: 2

Related Questions