0

I wanted to split a string

Input :

ABCDEFGHI

Output :

ABC, DEF, GHI

One way is by using For Loop.

string str = "ABCDEFGHI";

List<string> lst = new List<string>();

string temp = "";

for(int i = 0; i < str.Length; i++)
{
    temp = str[i].Tostring();

    if((i + 1) % 3 == 0)
    {
        lst.Add(temp);
        temp = "";
    }
}

string final_str = string.Join(", ", lst);

But how to do that using LINQ?

Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
  • 2
    Lots of options here: http://stackoverflow.com/questions/1396048/c-sharp-elegant-way-of-partitioning-a-list/ – Scroog1 May 18 '12 at 10:54

5 Answers5

0
var str = "ABCDEFGHI";

var result = testStr.Select(s => testStr.IndexOf(s))
                   .Where(i => i%3 == 0)
                   .Select(i => testStr.Substring(i,3))
                   .Aggregate("", (a,s) => a += s + ",");
sloth
  • 99,095
  • 21
  • 171
  • 219
Aidan
  • 4,783
  • 5
  • 34
  • 58
  • won't work if any character occurs more than once in the string – sloth May 18 '12 at 11:03
  • 1
    harsh to downvote for that, given that the example string was very specific. – Aidan May 18 '12 at 11:12
  • mmh, OK. You're right about the example string beeing very specific and not very clear; I removed the downvote. But the code Nikhil provided would work on other strings, and yours not. – sloth May 18 '12 at 11:18
0

With the help of MoreLinq

List<string> lst = str.Batch(3).Select(s => String.Join("",s)).ToList();
L.B
  • 114,136
  • 19
  • 178
  • 224
0

And another one (without MoreLinq):

var str = "ABCDEFGHI";
var tmp = str.Select((i, index) => new { i, index })
             .GroupBy(g => g.index / 3, e => e.i)
             .Select(g => String.Join("", g));
var final_string = String.Join(", ", tmp);
sloth
  • 99,095
  • 21
  • 171
  • 219
0

using MoreLinq.Batch

var result = str.Batch(3);

type of result is IEnumerable>, ToArray can be used to make it IEnumerable< char[] >

EDIT I forgot last join statement in the first glance

var finalStr = String.Join(",",str.Batch(3).Select(x=>new String(x.ToArray())))
Tilak
  • 30,108
  • 19
  • 83
  • 131
-1
String.Join("", str.Select((x, i) => (i + 1)%3 == 0 ? x + " " : x.ToString()))
BlueVoodoo
  • 3,626
  • 5
  • 29
  • 37
  • won't work since this adds an additional comma add the end of the string if the length of the string is divisible by three. – sloth May 18 '12 at 11:06
  • Ah yes, I didn't even see the comma. :) It can of course be trimmed which will make this call shorther than your version. – BlueVoodoo May 18 '12 at 11:09