例如:
string maskedString = MaskString("ABCDEFGHIJLK", 2, 3, 'X');
输出:ABXXXXXXXJLK
string maskedString = MaskString("123456", 2, 3, '*');
输出:12*456
string MaskString(string inputString, int leftUnMaskLength, int rightUnMaskLength, char maskCharacter)
{
//What is the simplest way to code this efficiently in C# .Net 3.5
}
答案 0 :(得分:3)
您可以使用String.Substring
方法获取字符串的开始和结束部分,并使用String
构造函数构建蒙版中间部分。你会得到这样的东西:
static string MaskString(string inputString, int leftUnMaskLength, int rightUnMaskLength, char mask)
{
if ((leftUnMaskLength + rightUnMaskLength) > inputString.Length)
return inputString;
return inputString.Substring(0, leftUnMaskLength) +
new string(mask, inputString.Length - (leftUnMaskLength + rightUnMaskLength)) +
inputString.Substring(inputString.Length - rightUnMaskLength);
}
答案 1 :(得分:0)
这是一个实现:
string MaskString(string inputString, int leftUnMaskLength, int rightUnMaskLength, char maskCharacter)
{
var output = new List<char>();
var inputLength = inputString.Length;
for(var q = 0; q < inputLength; q++)
{
if (q < leftUnMaskLength || q > (inputLength - (rightUnMaskLength + 1)))
{
output.Add(inputString[q]);
}
else
{
output.Add(maskCharacter);
}
}
return new String(output.ToArray());
}
答案 2 :(得分:0)
我写了下面的代码,除了一个字符串,用*
掩盖其内容的一半。您可以修改此代码以指定需要屏蔽的字符数。
public static string MaskedString(string originalString)
{
int halfLength;
string rightString;
var leftString = new StringBuilder();
string maskedString;
if ((originalString == "-") || (string.IsNullOrEmpty(originalString)))
{
maskedString = originalString;
}
else
{
if (originalString.Length % 2 == 0)
{
halfLength = originalString.Length / 2;
for (int i = 1; i <= halfLength; i++)
{
leftString.Append('*');
}
}
else
{
halfLength = (originalString.Length + 1) / 2;
for (int i = 1; i < halfLength; i++)
{
leftString.Append('*');
}
}
rightString = originalString.Substring(originalString.Length - halfLength);
maskedString = leftString + rightString;
}
return maskedString;
}
E.g;
Input - Reyan Chougle Output - ******Chougle