格式化字母数字字符串 [英] Formatting alphanumeric string
本文介绍了格式化字母数字字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有16个字母数字字符,例如一个字符串F4194E7CC775F003。我想它格式化为F419-4E7C-C775-F003。
I have a string with 16 alphanumeric characters, e.g. F4194E7CC775F003. I'd like to format it as F419-4E7C-C775-F003.
我试图用
string.Format("{0:####-####-####-####}","F4194E7CC775F003");
但是,这并不工作,因为它不是一个数值。
but this doesn't work since it's not a numeric value.
于是我想出了以下内容:
So I came up with the following:
public class DashFormatter : IFormatProvider, ICustomFormatter
{
public object GetFormat(Type formatType)
{
return this;
}
public string Format(string format, object arg, IFormatProvider formatProvider)
{
char[] chars = arg.ToString().ToCharArray();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < chars.Length; i++)
{
if (i > 0 && i % 4 == 0)
{
sb.Append('-');
}
sb.Append(chars[i]);
}
return sb.ToString();
}
}
和使用
string.Format(new DashFormatter(), "{0}", "F4194E7CC775F003");
我是能够解决的问题,但是我希望有一个更好/更简单的方法它?也许有些LINQ的魔力?
I was able to solve the problem, however I was hoping there is a better/simpler way to do it? Perhaps some LINQ magic?
感谢。
推荐答案
您可以做它没有Linq的一行:
You can do it in one line without Linq:
StringBuilder splitMe = new StringBuilder("F4194E7CC775F003");
string joined = splitMe.Insert(12, "-").Insert(8, "-").Insert(4, "-").ToString();
这篇关于格式化字母数字字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文