110,529
社区成员
发帖
与我相关
我的任务
分享
string txt = @"682419700600006803203233333A333333333EF7D8808AB24355F4C9F8A9FD8C4796574CA33933333333B416";
StringBuilder tmp = new StringBuilder();
char split = ' ';
for (var i = 0; i < txt.Length; i++)
{
tmp.Append(txt[i]);
if (i % 2 == 1 && i != txt.Length - 1)
{
tmp.Append(split);
}
}
Console.WriteLine(tmp.ToString());
string txt = @"682419700600006803203233333A333333333EF7D8808AB24355F4C9F8A9FD8C4796574CA33933333333B416";
StringBuilder sb = new StringBuilder(txt, 0, 2, (int)(txt.Length * 1.5));
for (int j = 2; j < txt.Length; j += 2)
sb.Append(' ').Append(txt, j, 2);
string result = sb.ToString();
目前能想到最快的方法@"(?<=^(?>(?:\w{2})+))"
static void Main(string[] args)
{
string txt = "419700600006803203233333A333333333EF7D8808AB24355F4C9F8A9FD8C4796574CA33933333333B416";
for (int i = 0; i < 8; i++) txt = txt + txt;
Measure(() =>
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < txt.Length; i++) { if ((i - 1) % 2 == 1)sb.Append(' '); sb.Append(txt[i]); }
string s2 = sb.ToString();
});
Measure(() =>
{
string s2 = Regex.Replace(txt, @"\w\w", "$0 ").TrimEnd();
});
Measure(() =>
{
string s2 = string.Join(" ", Regex.Split(txt, @"(?<=^(?:\w{2})+)"));
});
Measure(() =>
{
for (int i = 2; i < txt.Length; i += 3)
{
txt = txt.Insert(i, " ");
}
});
// 运行结果
// Elapsed: 0ms
// Elapsed: 8ms
// Elapsed: 19597ms
// Elapsed: 81ms
}
static void Measure(Action action)
{
Stopwatch sw = Stopwatch.StartNew();
action();
Console.WriteLine("Elapsed: {0}ms", sw.ElapsedMilliseconds);
}
string s = "682419700600006803203233333A333333333EF7D8808AB24355F4C9F8A9FD8C4796574CA33933333333B416";
for (int i = 2; i < s.Length; i +=3)
{
s = s.Insert(i, " ");
}
string txt = @"682419700600006803203233333A333333333EF7D8808AB24355F4C9F8A9FD8C4796574CA33933333333B416";
txt = string.Join(" ", Regex.Split(txt, @"(?<=^(?:\w{2})+)"));
Console.WriteLine(txt);