C# 如何屏蔽字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9705955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to mask string?
提问by mko
I have a string with value "1131200001103".
我有一个值为“1131200001103”的字符串。
How can I display it as a string in this format "11-312-001103" using Response.Write(value)?
如何使用 Response.Write(value) 将其显示为“11-312-001103”格式的字符串?
Thanks
谢谢
采纳答案by Olivier Jacot-Descombes
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.
假设您想在前 2 个空值的位置删除 2 个字符。
回答by Jon Skeet
Any reason you don't want to just use Substring?
您不想使用的任何理由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 which0s, admittedly...)
(我假设您是故意漏掉了两个 0 的?目前尚不清楚是哪个0,诚然......)
Obviously you should validate that the string is the right length first...
显然,您应该首先验证字符串的长度是否正确......
回答by skyfoot
You can try a regular expression and put this inside an extension method ToMaskedString()
您可以尝试使用正则表达式并将其放入扩展方法 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, "--");
}
}
Then call
然后打电话
respne.Write(value.ToMaskedString());
回答by CodeSlinger512
Maybe something like
也许像
string result = str.SubString(0, 2) + "-" + str.SubString(2, 3) + "-" + str.SubString(7);
str being the "11312000011103" string
str 是“11312000011103”字符串

