Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string by character count and store in string array [duplicate]

Tags:

c#

I have a string like this

abcdefghij

And I wast to split this string by 3 characters each. My desired output will be a string array containing this

abc
def
ghi
j

Is is possible using string.Split() method?

like image 730
None Avatar asked Sep 24 '26 11:09

None


1 Answers

This code will group the chars in groups of 3, and convert each group to a string.

string s = "abcdefghij";

var split = s.Select((c, index) => new {c, index})
    .GroupBy(x => x.index/3)
    .Select(group => group.Select(elem => elem.c))
    .Select(chars => new string(chars.ToArray()));

foreach (var str in split)
    Console.WriteLine(str);

prints

abc
def
ghi
j

Fiddle: http://dotnetfiddle.net/1PgFu7

like image 149
dcastro Avatar answered Sep 26 '26 00:09

dcastro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!