我有一个字符串,它现在的格式将用作序列号:
XXX1XXX2XXX3XXX4
我希望它格式化为:
XXX1-XXX2-XXX3-XXX4
我怎样才能做到这一点?
有很多方法可以做到这一点。:)
这是另一个:
string s = "XXX1XXX2XXX3XXX4";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.Length; ++i)
{
sb.Append(s[i]);
if ((i < s.Length-1) && ((i+1) % 4) == 0)
{
sb.Append('-');
}
}
s = sb.ToString();
Console.WriteLine(s);
string str="0123567236359783590203582835";
str.ToCharArray()
.Aggregate("",
(result, c) => result += ((!string.IsNullOrEmpty(result) && (result.Length+1) % 5 == 0)
? "-" : "")
+ c.ToString()
);
// --> 0123-5672-3635-9783-5902-0358-2835
StringBuilder init = new StringBuilder("XXX1XXX2XXX3XXX4");
string insertVal = "-";
for(int i=4, i<init.length;i=i+5)
{
init.insert(i, inserVal, 1);
}
尝试使用Linq
如下...
var s = "XXX1XXX2XXX3XXX4xx5x";
var list = Enumerable
.Range(0, s.Length/4)
.Select(i => s.Substring(i*4, 4))
.ToList();
var res = string.Join("-", list);
Console.WriteLine("{0}",res);