C # stuff functions custom implementation of sql function - phone number hidden middle four, and replace it with an asterisk

sql server has a function of Stuff, the specified function is to delete the specified character string starting position and insert a new string. Sql server in a very easy to implement mobile number hidden among four, replaced with asterisks. as follows:

stuff(a.LoginName,4,4,'****')

Unfortunately, C # does not have this function, a simple process:

public static string GetLoginNameDisplay(this string loginName)
{
    string result = "";
    result = loginName.Substring(0, 3) + "****" + loginName.Substring(7);
    return result;
}

The following is a general method I wrote, to achieve the stuff functions:

public static string Stuff(this string str,int startPosition,int length,char replaceChar)
{
    if (string.IsNullOrEmpty(str))
        return "";
    string result = "";
    if (startPosition <0)
        return "";
    result = str.Substring(0, startPosition) + "".PadLeft(length, replaceChar);
    var indexNew = startPosition + length;
    if (indexNew <= str.Length - 1)
        result += str.Substring(indexNew);
    return result;
}

 

 

Guess you like

Origin www.cnblogs.com/ashbur/p/12017938.html