How to mask string?

后端 未结 5 722
温柔的废话
温柔的废话 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:15

    Maybe something like

    string result = str.SubString(0, 2) + "-" + str.SubString(2, 3) + "-" + str.SubString(7);
    

    str being the "11312000011103" string

    0 讨论(0)
  • 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);
        }
    }
    
    0 讨论(0)
  • 2021-01-18 03:23

    You can try a regular expression and put this inside an extension method ToMaskedString()

    public static class StringExtensions
    {
        public static string ToMaskedString(this String value)
        {
            var pattern = "^(/d{2})(/d{3})(/d*)$";
            var regExp = new Regex(pattern);
            return regExp.Replace(value, "$1-$2-$3");
        }
    }
    

    Then call

    respne.Write(value.ToMaskedString());
    
    0 讨论(0)
  • 2021-01-18 03:30

    This produces the required result

    string result = Int64.Parse(s.Remove(5,2)).ToString("00-000-000000");
    

    assuming that you want to drop 2 characters at the position of the 2 first nulls.

    0 讨论(0)
  • 2021-01-18 03:30

    Any reason you don't want to just use Substring?

    string dashed = text.Substring(0, 2) + "-" +
                    text.Substring(2, 3) + "-" +
                    text.Substring(7);
    

    Or:

    string dashed = string.Format("{0}-{1}-{2}", text.Substring(0, 2),
                                  text.Substring(2, 3), text.Substring(7));
    

    (I'm assuming it's deliberate that you've missed out two of the 0s? It's not clear which 0s, admittedly...)

    Obviously you should validate that the string is the right length first...

    0 讨论(0)
提交回复
热议问题