每2个字符拆分字符串 [英] Split string by every 2 characters
问题描述
您好,
我只想在项目工作中完成一项小任务。
我想用每两个字符用':'拆分字符串。我在下面给出了详细的示例: -
如果输入字符串是 12345678 ,我看输出是 12:34:56:78
谢谢
Vasanth
Hello,
I just wanted one small task in my project work.
I want to split string with ':' by every two characters. I have shows detailed example below :-
If Input string is "12345678", i looking the output is "12:34:56:78"
Thanks
Vasanth
推荐答案
好的,既然我们要沿着LINQ路线走下去(参见解决方案#7),这里有一个更有效的方法::)
OK, since we're going down the LINQ route (see solution #7), here's a slightly more efficient method: :)
public static class ExtensionMethods
{
public static IEnumerable<T> DelimitWith<T>(this IEnumerable<T> source, T separator, int itemsPerGroup = 1)
{
if (source == null) throw new ArgumentNullException("source");
if (itemsPerGroup < 1) throw new ArgumentOutOfRangeException("itemsPerGroup");
return DelimitWithIterator(source, separator, itemsPerGroup);
}
private static IEnumerable<T> DelimitWithIterator<T>(IEnumerable<T> source, T separator, int itemsPerGroup)
{
int count = 0;
foreach (T item in source)
{
if (count == itemsPerGroup)
{
yield return separator;
count = 0;
}
checked
{
count++;
}
yield return item;
}
}
}
string source = "1234567890";
char[] resultChars = source.DelimitWith(':', 2).ToArray();
string result = new string(resultChars);
可能有更简单,更优雅的方法,但是...
There are probably simpler and more elegant ways to do this, but...
string s = "12345678";
StringBuilder sb = new StringBuilder();
int index = 0;
foreach (char c in s)
{
sb.AppendFormat("{0}{1}", c, (index++ & 1) == 0 ? "" : ":");
}
s = sb.ToString().Trim(':');
会这样做。
Will do it.
为了好玩它:OriginalGriff提供的代码示例稍有不同(请投票)对于OriginalGriff的答案,而不是这一个):
For the fun of it: a slight variation on the code example provided by OriginalGriff (please vote for OriginalGriff's answer, not this one):
string str = "123456789";
//check string is even in length
if (str.Length % 2 == 1) throw new ArgumentOutOfRangeException ("String length must be even");
StringBuilder sb = new StringBuilder();
int index = 0;
foreach (char c in str)
{
sb.Append(c);
if ((++index % 2) == 0) sb.Append(":");
}
str = sb.Remove(sb.Length - 1, 1).ToString();
如果你真的想要花哨,并尝试将循环迭代次数减少一半:
If you really want to get fancy, and try to reduce the number of loop iterations by half:
for (int i = 1, j = 0; i < (str.Length / 2); i += 2, j+= 2)
{
sb.Append(str[j]);
sb.Append(str[i]);
sb.Append(':');
}
str = sb.Remove(sb.Length - 1, 1).ToString();
这里使用的额外StringBuilder.Appends的成本是否超过执行循环次数的优势,并且消除了一个布尔测试:我的猜测是,在数百万次执行的情况下,它会略微加快。
Whether the "cost" of the extra StringBuilder.Appends used here "outweighs" the advantage of executing the loop half the number of times, and eliminating one boolean test: my guess is that it would be marginally faster in the context of millions of executions.
这篇关于每2个字符拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!