-5

I've got a problem. I have a string "3d8sAdTd6c" And I would need it to split it, so the conclusion would be:

3d
8s
Ad
Td
6c

If you could tell me how to do this I would be very grateful.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
R. Sepp
  • 21
  • 1

4 Answers4

1

Perhaps:

string[] result = str
    .Select((c, index ) => new{ c, index })
    .GroupBy(x => x.index / 2)
    .Select(xg => string.Join("", xg.Select(x => x.c)))
    .ToArray();

This groups every second character and uses string.Join to concat them to a string.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • Now that's beautiful my friend! – Mike Perrenoud Nov 13 '13 at 21:21
  • Along with this, I rather enjoy the Regex approach here: http://stackoverflow.com/questions/9932096/add-separator-to-string-at-every-n-characters In a nutshell: string.Join(Environment.NewLine, System.Text.RegularExpressions.Regex.Split(myString, "(?<=^(.{2})+)"))); – trope Nov 13 '13 at 21:55
0

To split any string into pairs of two characters:

/// <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);
}

Usage:

var pairs = SplitIntoPairs("3d8sAdTd6c");

Result:

3d
8s
Ad
Td
6c
Daniel A.A. Pelsmaeker
  • 47,471
  • 20
  • 111
  • 157
  • 1
    I like how the documentation for the function is just as long as the function itself. – gunr2171 Nov 13 '13 at 21:15
  • 1
    @gunr2171 Once you start using the function, you don't see its code. The documentation is _all you have_ (it shows up in IntelliSense), so I _always_ write documentation the very moment I write the function. – Daniel A.A. Pelsmaeker Nov 13 '13 at 21:17
0

Something like below should work with loops.

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);
apollosoftware.org
  • 12,161
  • 4
  • 48
  • 69
0
string input = "3d8sAdTd6c";
for (int i = 0; i < input.Length; i+=2) {
    Console.WriteLine(input.Substring(i,2));
}
Dustin Fain
  • 120
  • 8