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.
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.
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.
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
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);
string input = "3d8sAdTd6c";
for (int i = 0; i < input.Length; i+=2) {
Console.WriteLine(input.Substring(i,2));
}