【转载】C#隐私信息(银行账户,身份证号码,名字)中间部分特殊字符替换(*)

原文地址:https://www.cnblogs.com/kewolf/p/4692630.html

/// <summary>
/// 将传入的字符串中间部分字符替换成特殊字符
/// </summary>
/// <param name="value">需要替换的字符串</param>
/// <param name="startLen">前保留长度</param>
/// <param name="endLen">尾保留长度</param>
/// <param name="replaceChar">特殊字符</param>
/// <returns>被特殊字符替换的字符串</returns>
private static string ReplaceWithSpecialChar(string value, int startLen = 4, int endLen = 4, char specialChar = '*')
{
    try
    {
        int lenth = value.Length - startLen - endLen;
 
        string replaceStr = value.Substring(startLen, lenth);
 
        string specialStr = string.Empty;
 
        for (int i = 0; i < replaceStr.Length; i++)
        {
            specialStr += specialChar;
        }
 
        value = value.Replace(replaceStr, specialStr);
    }
    catch (Exception)
    {
        throw;
    }
 
    return value;
}

调用以及效果如下:

ReplaceWithSpecialChar("柯小呆", 1, 0,'*') -->Result: 柯*呆

ReplaceWithSpecialChar("622212345678485") -->Result: 6222*******8485

ReplaceWithSpecialChar("622212345678485", 4 , 4 , '*') -->Result: 6222*******8485

posted @ 2019-04-02 09:38  吃辣椒的小毛驴  阅读(605)  评论(0编辑  收藏  举报