/// <summary>
/// 用*号隐藏部分用户名、手机号
/// </summary>
/// <param name="userName"></param>
/// <returns></returns>
public static string ConverUserNameToAnonymous(this string userName)
{
string userNameAfterReplaced;
try
{
int nameLength = userName.Length;
if (nameLength <= 2 && nameLength >= 1)
{
if (nameLength == 1)
{
userNameAfterReplaced = "*";
}
else
{
userNameAfterReplaced = "**";
}
}
else
{
int num1, num2, num3;
num2 = (int)Math.Ceiling((double)nameLength / 3);
num1 = (int)Math.Floor((double)nameLength / 3);
num3 = nameLength - num1 - num2;
StringBuilder starStr = new StringBuilder();
for (int i = 0; i < num2; i++)
{
starStr.Append("*");
}
userNameAfterReplaced = $"{userName.Substring(0, num1)}{starStr}{userName.Substring(num1 + num2, num3)}";
}
}
catch (Exception)
{
userNameAfterReplaced = userName;
}
return userNameAfterReplaced;
}
引用示例:
user.NickName = user.NickName.ConverUserNameToAnonymous();
|