如何使用C#审查字符串中的前10个字符

4 c# linq arrays lambda char

所以我想创建一个信用卡编码器(如果是偶数的话),该编码器接受一个字符串,并将字符串的前10位数字放入,因为'*' 这是我想出的代码:

public static string[] ToCencoredString(this string str)   
{
    char[] array = Enumerable.Repeat('*', str.Length-1).ToArray();
    array = array.Select((cha, index) =>
    {
        if (index < 10)
           array[index] = str[index];
    });
}
Run Code Online (Sandbox Code Playgroud)

(忽略函数返回的事实,string[]还有另一部分不相关的代码)

我不知道为什么,但是我不断得到ArgumentNullException,因为在array女巫is中没有一个单一的值null

我究竟做错了什么?

and*_*952 7

将其更改为更简单的方法是什么:

var result = string.Concat(Enumerable.Repeat("*", 10)) + str.Substring(10);
Run Code Online (Sandbox Code Playgroud)


Tim*_*ter 5

我会使用String.Substring字符串构造函数一起使用这个更有效的版本:

public static string ToCencoredString(this string str, int length = 10)
{
    if (String.IsNullOrEmpty(str)) return str;
    string censored = new string('*', length);
    if (str.Length <= length) return censored;
    return censored + str.Substring(length);
}
Run Code Online (Sandbox Code Playgroud)