简体   繁体   English

如何在第一个字符后屏蔽字符串

[英]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:如何用逗号后面的名称用X屏蔽string并返回:

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?任何人都对如何以更有效的方式实现相同的结果有更好的想法?

Another option, using Regex.Matches to select the name parts except the first letter.另一种选择,使用Regex.Matches选择除第一个字母之外的名称部分。 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.然后将Matches集合传递给 Linq 的Aggregate()方法以执行替换。
A StringBuilder is used to store the strings generated by its own Replace() method: StringBuilder用于存储由其自己的Replace()方法生成的字符串:

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
static string MaskName(string name)
    {
        string maskedString = string.Empty;

        string[] names = name.Split(',');
        if (names.Length > 0)
        {
            maskedString = names[0] + ",";
        }
        if (names.Length > 1)
        {
            string[] arrName = names[1].Split(' ');
            foreach (string s in arrName)
            {
                if (s.Length > 0)
                    maskedString += " " + s[0].ToString().PadRight(s.Length, 'X');
            }
        }
        return maskedString;
    }
Using This code..

    static string MaskName(string name)
    {
        string maskedString = string.Empty;

        string[] names = name.Split(',');
        if (names.Length > 0)
        {
            maskedString = names[0] + ",";
        }
        if (names.Length > 1)
        {
            string[] arrName = names[1].Split(' ');
            foreach (string s in arrName)
            {
                if (s.Length > 0)
                    maskedString += " " + s[0].ToString().PadRight(s.Length, 'X');
            }
        }
        return maskedString;
    }

Output :-输出 :- 在此处输入图片说明

Try This尝试这个

 private string ReturnMaskedName(string name)
        {
            string temporary = "";
            var newname = (name.Split(new string[] { "," }, StringSplitOptions.None)[1].Trim().Split(new String[] { " " }, StringSplitOptions.None));

            foreach (string allnames in newname)
            {
                temporary = temporary + " " + allnames[0].ToString() + new string('X', allnames.Length - 1);
            }
            return name.Split(new string[] { " " }, StringSplitOptions.None)[0] + " " + temporary;
        }

Efficient way of masking without Split , Regex , and using System.Linq :没有SplitRegexusing System.Linq有效屏蔽方法:

For C# version < 7.2:对于 C# 版本 < 7.2:

static string MaskName(string name)
{
    int indexOfComma = name.IndexOf(',');

    if (indexOfComma != -1)
    {
        char[] temp = name.ToCharArray();

        bool isFirstChar = true;

        for (int i = indexOfComma + 1; i < temp.Length; i++)
        {
            if (temp[i] == ' ')
                isFirstChar = true;
            else if (isFirstChar)
                isFirstChar = false;
            else
                temp[i] = 'X';
        }

        return new string(temp);
    }
    else
    {
        return name;
    }
}

For C# version >= 7.2:对于 C# 版本 >= 7.2:

static string MaskName(ReadOnlySpan<char> name)
{
    int indexOfComma = name.IndexOf(',');

    if (indexOfComma != -1)
    {
        Span<char> temp = stackalloc char[name.Length];

        name.CopyTo(temp);

        bool isFirstChar = true;

        for (int i = indexOfComma + 1; i < temp.Length; i++)
        {
            if (temp[i] == ' ')
                isFirstChar = true;
            else if (isFirstChar)
                isFirstChar = false;
            else
                temp[i] = 'X';
        }

        return new string(temp);
    }
    else
    {
        return name.ToString();
    }
}
private string MaskName(string name)
{
    var parts = name.Split(',');
    var subparts = parts[1].Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);

    for (var i = 0; i < subparts.Length; i++)
    {
        var subpart = subparts[i];

        subparts[i] = subpart[0] + new string('X', subpart.Length - 1);
    }

    return parts[0] + ", " + string.Join(" ", subparts);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 jquery 掩码插件在第一个字符位置移动 cursor? - How to move cursor at first character positon using jquery mask plugin? 在“第一个”空格字符之前和之后获取字符串 - Take string before and after 'First' space character 如何提取第一个字符和之后的数字,直到在字符串中找到字符 (az) - C# 2.0 - How to extract first character and numbers after that until find a character (a-z) in a string - C# 2.0 如何使用C#在字符串中的第一个数字值之后用指定的字符替换空格/字符? - How to replace space/character with specified character after first numeric value in string using C#? 匹配字符串后,在第一次出现字符时拆分字符串 - Split a string at the first occurrence of a character after matching string "如何获取字符串的前五个字符" - How to get the first five character of a String 如何从 XAML 中的字符串中去除第一个字符 - How to Strip First Character From String in XAML C#:如何获取字符串的第一个字符? - C#: how to get first character of a string? 拆分字符串如何不包含第一个字符? - How can split string not include first character? 在第一个字符之后替换字符串中所有出现的字符 - Replace all occurrences of a character in a string after the first one
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM