C# 用 *? 屏蔽掉字符串的前 12 个字符。

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9035192/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 05:42:19  来源:igfitidea点击:

Mask out part first 12 characters of string with *?

c#.netc#-4.0

提问by Xaisoft

How can I take the value 123456789012345or 1234567890123456and turn it into:

我如何获取价值1234567890123451234567890123456将其转换为:

************2345and ************3456

************2345************3456

The difference between the strings above is that one contains 15 digits and the other contains 16.

上述字符串的区别在于,一个包含 15 个数字,另一个包含 16 个。

I have tried the following, but it does not keep the last 4 digits of the 15 digit number and now matter what the length of the string, be it 13, 14, 15, or 16, I want to mask all beginning digits with a *, but keep the last 4. Here is what I have tried:

我尝试了以下方法,但它没有保留 15 位数字的最后 4 位数字,现在不管字符串的长度是 13、14、15 还是 16,我想用*,但保留最后 4 个。这是我尝试过的:

String.Format("{0}{1}", "************", str.Substring(11, str.Length - 12))

采纳答案by Darin Dimitrov

using System;

class Program
{
    static void Main()
    {
        var str = "1234567890123456";
        if (str.Length > 4)
        {
            Console.WriteLine(
                string.Concat(
                    "".PadLeft(12, '*'), 
                    str.Substring(str.Length - 4)
                )
            );
        }
        else
        {
            Console.WriteLine(str);
        }
    }
}

回答by John Feminella

Try this:

尝试这个:

var maskSize = ccDigits.Length - 4;
var mask = new string('*', maskSize) + ccDigits.Substring(maskSize);

回答by sll

LINQ:

林克:

char maskBy = '*'; 
string input = "123456789012345";
int count = input.Length <= 4 ? 0 : input.Length - 4; 
string output = new string(input.Select((c, i) => i < count ? maskBy : c).ToArray()); 

回答by Mike Hofer

Easiest way: Create an extension method to extract the last four digits. Use that in your String.Format call.

最简单的方法:创建一个扩展方法来提取最后四位数字。在您的 String.Format 调用中使用它。

For example:

例如:

public static string LastFour(this string value)
{
    if (string.IsNullOrEmpty(value) || value.length < 4)
    {
        return "0000";
    }
    return value.Substring(value.Length - 4, 4) 
}

In your code:

在您的代码中:

String.Format("{0}{1}", "************", str.LastFour());

In my opinion, this leads to more readable code, and it's reusable.

在我看来,这会导致代码更具可读性,并且是可重用的。

EDIT:Perhaps not the easiest way, but an alternative way that may produce more maintainable results. <shrug/>

编辑:也许不是最简单的方法,而是一种可能产生更易于维护的结果的替代方法。<耸肩/>

回答by Daniel Pe?alba

Try the following:

请尝试以下操作:

    private string MaskString(string s)
    {
        int NUM_ASTERISKS = 4;

        if (s.Length < NUM_ASTERISKS) return s;

        int asterisks = s.Length - NUM_ASTERISKS;
        string result = new string('*', asterisks);
        result += s.Substring(s.Length - NUM_ASTERISKS);
        return result;
    }

回答by Bob Vale

Regex with a match evaluator will do the job

带有匹配评估器的正则表达式将完成这项工作

string filterCC(string source) {
  var x=new Regex(@"^\d+(?=\d{4}$)");
  return x.Replace(source,match => new String('*',match.Value.Length));
}

This will match any number of digits followed by 4 digits and the end (it won't include the 4 digits in the replace). The replace function will replace the match with a string of * of equal length.

这将匹配任意数量的数字,后跟 4 位数字和结尾(它不会在替换中包含 4 位数字)。替换函数将用等长的 * 字符串替换匹配项。

This has the additional benefit that you could use it as a validation algorthim too. Change the first + to {11,12} to make it match a total of 15 or 16 chars and then you can use x.IsMatchto determine validity.

这还有一个额外的好处,您也可以将其用作验证算法。将第一个 + 更改为 {11,12} 以使其匹配总共 15 或 16 个字符,然后您可以使用它x.IsMatch来确定有效性。

EDIT

编辑

Alternatively if you always want a 16 char result just use

或者,如果您总是想要 16 个字符的结果,请使用

 return x.Replace(source,new String('*',12));

回答by anjunatl

static private String MaskInput(String input, int charactersToShowAtEnd)
{
  if (input.Length < charactersToShowAtEnd)
  {
    charactersToShowAtEnd = input.Length;
  }
  String endCharacters = input.Substring(input.Length - charactersToShowAtEnd);
  return String.Format(
    "{0}{1}", 
    "".PadLeft(input.Length - charactersToShowAtEnd, '*'), 
    endCharacters
    );
}

Adjust the function header as required, call with:

根据需要调整函数头,调用:

MaskInput("yourInputHere", 4);

回答by Fabio Luz

A simple way

一个简单的方法

   string s = "1234567890123"; // example
   int l = s.Length;
   s = s.Substring(l - 4);
   string r = new string('*', l);
   r = r + s;

回答by Mark Mintoff

Try this out:

试试这个:

static string Mask(string str)
{
    if (str.Length <= 4) return str;
    Regex rgx = new Regex(@"(.*?)(\d{4})$");
    string result = String.Empty;
    if (rgx.IsMatch(str))
    {
        for (int i = 0; i < rgx.Matches(str)[0].Groups[1].Length; i++)
            result += "*";
        result += rgx.Matches(str)[0].Groups[2];
        return result;
    }
    return str;
}

回答by Chris Dunaway

Something like this:

像这样的东西:

string s = "1234567890123"; // example
string result = s.Substring(s.Length - 4).PadLeft(s.Length, '*');

This will mask all but the last four characters of the string. It assumes that the source string is at least 4 characters long.

这将屏蔽除字符串的最后四个字符之外的所有字符。它假定源字符串至少有 4 个字符长。