C#手机号中间变*号,隐藏敏感信息方法(身份证号、银行卡号等)
此方法适用于隐藏手机号、银行卡号等信息,如:1:186****9212 手机号
2:622202********2688银行卡号
3:654301********0888身份证号
....... 还有很多
代码:
/// <summary>
/// 隐藏敏感信息
/// </summary>
/// <param name="info">信息实体</param>
/// <param name="left">左边保留的字符数</param>
/// <param name="right">右边保留的字符数</param>
/// <param name="basedOnLeft">当长度异常时,是否显示左边
/// <code>true</code>显示左边,<code>false</code>显示右边
/// </param>
/// <returns></returns>
public static string HideSensitiveInfo(string info, int left, int right, bool basedOnLeft=true)
{
if (String.IsNullOrEmpty(info))
{
return "";
}
StringBuilder sbText = new StringBuilder();
int hiddenCharCount = info.Length - left - right;
if (hiddenCharCount > 0)
{
string prefix = info.Substring(0, left), suffix = info.Substring(info.Length - right);
sbText.Append(prefix);
for (int i = 0; i < hiddenCharCount; i++)
{
sbText.Append("*");
}
sbText.Append(suffix);
}
else
{
if (basedOnLeft)
{
if (info.Length > left && left > 0)
{
sbText.Append(info.Substring(0, left) + "****");
}
else
{
sbText.Append(info.Substring(0, 1) + "****");
}
}
else
{
if (info.Length > right && right > 0)
{
sbText.Append("****" + info.Substring(info.Length - right));
}
else
{
sbText.Append("****" + info.Substring(info.Length - 1));
}
}
}
return sbText.ToString();
}
111 (。◕ˇ∀ˇ◕) 1111111111111 做个记号,下次好找! 很牛逼
页:
[1]