How to mask string?

二次信任 提交于 2019-12-01 17:39:06

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.

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...

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());

Maybe something like

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

str being the "11312000011103" string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!