-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.

3
  • 8
    Have you made any research? Do you really think this is so unique problem that it has never been asked? Commented Nov 13, 2013 at 21:07
  • There's a pretty useful implementation of something like that here: stackoverflow.com/a/1450797/328193 Commented Nov 13, 2013 at 21:09
  • 1
    -1 for zero research effort. Commented Nov 13, 2013 at 21:10

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Now that's beautiful my friend!
Along with this, I rather enjoy the Regex approach here: stackoverflow.com/questions/9932096/… In a nutshell: string.Join(Environment.NewLine, System.Text.RegularExpressions.Regex.Split(myString, "(?<=^(.{2})+)")));
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);

Comments

0
string input = "3d8sAdTd6c";
for (int i = 0; i < input.Length; i+=2) {
    Console.WriteLine(input.Substring(i,2));
}

Comments

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

2 Comments

I like how the documentation for the function is just as long as the function itself.
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.