我遇到了问题。我有一个字符串"3d8sAdTd6c"
我需要它来分割它,所以结论将是:
3d
8s
Ad
Td
6c
如果你能告诉我怎么做,我将非常感激。
答案 0 :(得分:1)
也许:
string[] result = str
.Select((c, index ) => new{ c, index })
.GroupBy(x => x.index / 2)
.Select(xg => string.Join("", xg.Select(x => x.c)))
.ToArray();
这会对每隔一个字符进行分组,并使用string.Join
将它们连接成一个字符串。
答案 1 :(得分:0)
将任意字符串拆分为两个字符对:
/// <summary>
/// Split a string into pairs of two characters.
/// </summary>
/// <param name="str">The string to split.</param>
/// <returns>An enumerable sequence of pairs of characters.</returns>
/// <remarks>
/// When the length of the string is not a multiple of two,
/// the final character is returned on its own.
/// </remarks>
public static IEnumerable<string> SplitIntoPairs(string str)
{
if (str == null) throw new ArgumentNullException("str");
int i = 0;
for (; i + 1 < str.Length; i += 2)
{
yield return str.Substring(i, 2);
}
if (i < str.Length)
yield return str.Substring(str.Length - 1);
}
用法:
var pairs = SplitIntoPairs("3d8sAdTd6c");
结果:
3d 8s Ad Td 6c
答案 2 :(得分:0)
下面的内容应该适用于循环。
string str = "3d8sAdTd6c";
string newstr = "";
int size = 2;
int stringLength = str.Length;
for (int i = 0; i < stringLength ; i += size)
{
if (i + size > stringLength) size = stringLength - i;
newstr = newstr + str.Substring(i, size) + "\r\n";
}
Console.WriteLine(newstr);
答案 3 :(得分:0)
string input = "3d8sAdTd6c";
for (int i = 0; i < input.Length; i+=2) {
Console.WriteLine(input.Substring(i,2));
}