-5

我有问题。我有一个字符串"3d8sAdTd6c",我需要它来拆分它,所以结论是:

3d
8s
Ad
Td
6c

如果你能告诉我如何做到这一点,我将不胜感激。

4

4 回答 4

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将它们连接到一个字符串。

于 2013-11-13T21:16:47.940 回答
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
广告
时差
6c
于 2013-11-13T21:12:26.890 回答
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);
于 2013-11-13T21:14:38.367 回答
0
string input = "3d8sAdTd6c";
for (int i = 0; i < input.Length; i+=2) {
    Console.WriteLine(input.Substring(i,2));
}
于 2013-11-13T21:18:51.170 回答