Masks first name of a string











up vote
4
down vote

favorite












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.










share|improve this question






















  • So Muhammad Ali is(are) a first name(s)?
    – SeM
    Nov 22 at 12:08












  • @SeM In some cases, Muhammad Ali can be a first name, yes.
    – Ahmad
    Nov 22 at 12:10






  • 4




    So how about grabbing the text between "Dear" and the comma, and removing all words except the last?
    – stuartd
    Nov 22 at 12:12










  • This looks like could be solved using regex. Does the text will always have this pattern? "Dear <person>, Thank you for coming"
    – Pedro Lima
    Nov 22 at 12:12






  • 3




    Without knowing what part of the string is actually a "first name" it's simply impossible to do that reliably. All you can do is to try to guess what is it and hope they all follow the same pattern, which is obviously wrong.
    – Alejandro
    Nov 22 at 12:43















up vote
4
down vote

favorite












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.










share|improve this question






















  • So Muhammad Ali is(are) a first name(s)?
    – SeM
    Nov 22 at 12:08












  • @SeM In some cases, Muhammad Ali can be a first name, yes.
    – Ahmad
    Nov 22 at 12:10






  • 4




    So how about grabbing the text between "Dear" and the comma, and removing all words except the last?
    – stuartd
    Nov 22 at 12:12










  • This looks like could be solved using regex. Does the text will always have this pattern? "Dear <person>, Thank you for coming"
    – Pedro Lima
    Nov 22 at 12:12






  • 3




    Without knowing what part of the string is actually a "first name" it's simply impossible to do that reliably. All you can do is to try to guess what is it and hope they all follow the same pattern, which is obviously wrong.
    – Alejandro
    Nov 22 at 12:43













up vote
4
down vote

favorite









up vote
4
down vote

favorite











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.










share|improve this question













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.







c#






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 22 at 12:05









AppeShopper

388




388












  • So Muhammad Ali is(are) a first name(s)?
    – SeM
    Nov 22 at 12:08












  • @SeM In some cases, Muhammad Ali can be a first name, yes.
    – Ahmad
    Nov 22 at 12:10






  • 4




    So how about grabbing the text between "Dear" and the comma, and removing all words except the last?
    – stuartd
    Nov 22 at 12:12










  • This looks like could be solved using regex. Does the text will always have this pattern? "Dear <person>, Thank you for coming"
    – Pedro Lima
    Nov 22 at 12:12






  • 3




    Without knowing what part of the string is actually a "first name" it's simply impossible to do that reliably. All you can do is to try to guess what is it and hope they all follow the same pattern, which is obviously wrong.
    – Alejandro
    Nov 22 at 12:43


















  • So Muhammad Ali is(are) a first name(s)?
    – SeM
    Nov 22 at 12:08












  • @SeM In some cases, Muhammad Ali can be a first name, yes.
    – Ahmad
    Nov 22 at 12:10






  • 4




    So how about grabbing the text between "Dear" and the comma, and removing all words except the last?
    – stuartd
    Nov 22 at 12:12










  • This looks like could be solved using regex. Does the text will always have this pattern? "Dear <person>, Thank you for coming"
    – Pedro Lima
    Nov 22 at 12:12






  • 3




    Without knowing what part of the string is actually a "first name" it's simply impossible to do that reliably. All you can do is to try to guess what is it and hope they all follow the same pattern, which is obviously wrong.
    – Alejandro
    Nov 22 at 12:43
















So Muhammad Ali is(are) a first name(s)?
– SeM
Nov 22 at 12:08






So Muhammad Ali is(are) a first name(s)?
– SeM
Nov 22 at 12:08














@SeM In some cases, Muhammad Ali can be a first name, yes.
– Ahmad
Nov 22 at 12:10




@SeM In some cases, Muhammad Ali can be a first name, yes.
– Ahmad
Nov 22 at 12:10




4




4




So how about grabbing the text between "Dear" and the comma, and removing all words except the last?
– stuartd
Nov 22 at 12:12




So how about grabbing the text between "Dear" and the comma, and removing all words except the last?
– stuartd
Nov 22 at 12:12












This looks like could be solved using regex. Does the text will always have this pattern? "Dear <person>, Thank you for coming"
– Pedro Lima
Nov 22 at 12:12




This looks like could be solved using regex. Does the text will always have this pattern? "Dear <person>, Thank you for coming"
– Pedro Lima
Nov 22 at 12:12




3




3




Without knowing what part of the string is actually a "first name" it's simply impossible to do that reliably. All you can do is to try to guess what is it and hope they all follow the same pattern, which is obviously wrong.
– Alejandro
Nov 22 at 12:43




Without knowing what part of the string is actually a "first name" it's simply impossible to do that reliably. All you can do is to try to guess what is it and hope they all follow the same pattern, which is obviously wrong.
– Alejandro
Nov 22 at 12:43












6 Answers
6






active

oldest

votes

















up vote
2
down vote













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 :)






share|improve this answer






























    up vote
    1
    down vote













    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






    share|improve this answer






























      up vote
      1
      down vote













      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






      share|improve this answer






























        up vote
        1
        down vote













        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");





        share|improve this answer






























          up vote
          0
          down vote













          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





          share|improve this answer






























            up vote
            0
            down vote













            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];
            }





            share|improve this answer





















              Your Answer






              StackExchange.ifUsing("editor", function () {
              StackExchange.using("externalEditor", function () {
              StackExchange.using("snippets", function () {
              StackExchange.snippets.init();
              });
              });
              }, "code-snippets");

              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "1"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














              draft saved

              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53430646%2fmasks-first-name-of-a-string%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              6 Answers
              6






              active

              oldest

              votes








              6 Answers
              6






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes








              up vote
              2
              down vote













              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 :)






              share|improve this answer



























                up vote
                2
                down vote













                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 :)






                share|improve this answer

























                  up vote
                  2
                  down vote










                  up vote
                  2
                  down vote









                  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 :)






                  share|improve this answer














                  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 :)







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 22 at 12:45

























                  answered Nov 22 at 12:33









                  Alex Domenici

                  14626




                  14626
























                      up vote
                      1
                      down vote













                      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






                      share|improve this answer



























                        up vote
                        1
                        down vote













                        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






                        share|improve this answer

























                          up vote
                          1
                          down vote










                          up vote
                          1
                          down vote









                          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






                          share|improve this answer














                          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







                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Nov 22 at 12:55

























                          answered Nov 22 at 12:41









                          Dhanushka Dayawansha

                          31119




                          31119






















                              up vote
                              1
                              down vote













                              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






                              share|improve this answer



























                                up vote
                                1
                                down vote













                                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






                                share|improve this answer

























                                  up vote
                                  1
                                  down vote










                                  up vote
                                  1
                                  down vote









                                  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






                                  share|improve this answer














                                  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







                                  share|improve this answer














                                  share|improve this answer



                                  share|improve this answer








                                  edited Nov 22 at 13:05

























                                  answered Nov 22 at 12:59









                                  SeM

                                  4,36511529




                                  4,36511529






















                                      up vote
                                      1
                                      down vote













                                      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");





                                      share|improve this answer



























                                        up vote
                                        1
                                        down vote













                                        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");





                                        share|improve this answer

























                                          up vote
                                          1
                                          down vote










                                          up vote
                                          1
                                          down vote









                                          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");





                                          share|improve this answer














                                          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");






                                          share|improve this answer














                                          share|improve this answer



                                          share|improve this answer








                                          edited Nov 22 at 15:05

























                                          answered Nov 22 at 13:07









                                          Fabjan

                                          9,61921439




                                          9,61921439






















                                              up vote
                                              0
                                              down vote













                                              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





                                              share|improve this answer



























                                                up vote
                                                0
                                                down vote













                                                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





                                                share|improve this answer

























                                                  up vote
                                                  0
                                                  down vote










                                                  up vote
                                                  0
                                                  down vote









                                                  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





                                                  share|improve this answer














                                                  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






                                                  share|improve this answer














                                                  share|improve this answer



                                                  share|improve this answer








                                                  edited Nov 22 at 13:42

























                                                  answered Nov 22 at 12:51









                                                  C.RaysOfTheSun

                                                  56527




                                                  56527






















                                                      up vote
                                                      0
                                                      down vote













                                                      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];
                                                      }





                                                      share|improve this answer

























                                                        up vote
                                                        0
                                                        down vote













                                                        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];
                                                        }





                                                        share|improve this answer























                                                          up vote
                                                          0
                                                          down vote










                                                          up vote
                                                          0
                                                          down vote









                                                          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];
                                                          }





                                                          share|improve this answer












                                                          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];
                                                          }






                                                          share|improve this answer












                                                          share|improve this answer



                                                          share|improve this answer










                                                          answered Nov 22 at 14:38









                                                          Magnus

                                                          35.7k75490




                                                          35.7k75490






























                                                              draft saved

                                                              draft discarded




















































                                                              Thanks for contributing an answer to Stack Overflow!


                                                              • Please be sure to answer the question. Provide details and share your research!

                                                              But avoid



                                                              • Asking for help, clarification, or responding to other answers.

                                                              • Making statements based on opinion; back them up with references or personal experience.


                                                              To learn more, see our tips on writing great answers.





                                                              Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                                              Please pay close attention to the following guidance:


                                                              • Please be sure to answer the question. Provide details and share your research!

                                                              But avoid



                                                              • Asking for help, clarification, or responding to other answers.

                                                              • Making statements based on opinion; back them up with references or personal experience.


                                                              To learn more, see our tips on writing great answers.




                                                              draft saved


                                                              draft discarded














                                                              StackExchange.ready(
                                                              function () {
                                                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53430646%2fmasks-first-name-of-a-string%23new-answer', 'question_page');
                                                              }
                                                              );

                                                              Post as a guest















                                                              Required, but never shown





















































                                                              Required, but never shown














                                                              Required, but never shown












                                                              Required, but never shown







                                                              Required, but never shown

































                                                              Required, but never shown














                                                              Required, but never shown












                                                              Required, but never shown







                                                              Required, but never shown







                                                              Popular posts from this blog

                                                              Contact image not getting when fetch all contact list from iPhone by CNContact

                                                              count number of partitions of a set with n elements into k subsets

                                                              A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks