How to mask string?

后端 未结 5 783
温柔的废话
温柔的废话 2021-01-18 02:51

I have a string with value \"1131200001103\".

How can I display it as a string in this format \"11-312-001103\" using Response.Write(value)?

Thanks

5条回答
  •  误落风尘
    2021-01-18 03:17

    I wrote a quick extension method for same / similar purpose (similar in a sense that there's no way to skip characters).

    Usage:

    var testString = "12345";
    var maskedString = testString.Mask("##.## #"); // 12.34 5
    

    Method:

    public static string Mask(this string value, string mask, char substituteChar = '#')
    {
        int valueIndex = 0;
        try
        {
            return new string(mask.Select(maskChar => maskChar == substituteChar ? value[valueIndex++] : maskChar).ToArray());
        }
        catch (IndexOutOfRangeException e)
        {
            throw new Exception("Value too short to substitute all substitute characters in the mask", e);
        }
    }
    

提交回复
热议问题