屏蔽字符串的名字

时间:2018-11-22 12:05:43

标签: c#

如何有效屏蔽字符串中的名字?

输入:尊敬的Elaine Jasper,谢谢您的光临

输出:亲爱的贾斯珀,谢谢您的光临

输入:亲爱的穆罕默德·阿里·优素福,谢谢您的光临

输出:亲爱的********优素福,谢谢您的光临

输入:尊敬的优素福,谢谢您的光临

输出:尊敬的优素福,谢谢您的光临

目前,我可以删除逗号前的所有内容,

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

但是我不确定如何保留姓氏。

该消息用于记录日志,客户端请求屏蔽名字。

6 个答案:

答案 0 :(得分:2)

这是应该可以帮助您的功能。请注意,可以对其进行更多优化以提高性能,并且请注意,该函数假定姓氏是一个单词。

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

运行程序,输出将是:

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.

希望有帮助:)

答案 1 :(得分:1)

尝试

  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

答案 2 :(得分:1)

您可以使用String.Split Method将句子分为两部分,然后从第一部分开始,该部分包含单词Dear和您的全名,仅取名字,将其掩盖并撰写一个新的名字

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

用法:

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

输出:

  

亲爱的****** Jasper,谢谢您的光临

     

亲爱的******** ***优素福,谢谢您的光临

     

亲爱的优素福,谢谢您的光临

参考: DotNetFiddle Example String.Split Method String.Join method {{3 }} Enumerable.Select Method Enumerable.Skip Method

答案 3 :(得分:1)

好吧,您可以按照以下方式进行操作:

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

和用法:

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

答案 4 :(得分:0)

以下代码段中的方法的工作方式是:首先抓取输入字符串的第一段(逗号左侧的部分),然后从上述字符串(位于首尾之间)获取假定的名字空格),然后将其屏蔽。 :)

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

上述方法的输出将类似于

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

答案 5 :(得分:0)

我的贡献:

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