C#: How to split text block into chunks by fixed boundary?

Viewed 34

Is there any simple way to split a block of text (no matter of form, may by List<string> or string[] array) in C#? I'm kind of newbie and looking for solution... Input form is something of:

Not important line 1
Not important other line
FIXED BOUNDARY
Line 1 for chunk 1
Line 2 for chunk 1
...
Line n for chunk 1
FIXED BOUNDARY
Line 1 for chunk 2
Line 2 for chunk 2
...
Line n for chunk 2
FIXED BOUNDARY
Line 1 for chunk 3
...
Repeated for end of input lines

In the end, I need to get List<List<string>> or List<string[]> with chunks: each element of list should contains all lines belongs to chunk from 1 to n (including boundary or not: it doesn't matter):

Chunk 1:

Line 1 for chunk 1
Line 2 for chunk 1
...
Line n for chunk 1

Chunk 2:

Line 1 for chunk 2
Line 2 for chunk 2
...
Line n for chunk 2

and so on. The number of chunks may vary, so I don't know how many chunks may be in input string list. How should I split it? Is there any library for that kind of text transformation? Please help guys...

1 Answers

Multiple application of String.Split combined with LINQ methods will work:

var text = 
@"Not important line 1
Not important other line
FIXED BOUNDARY
Line 1 for chunk 1
Line 2 for chunk 1
...
Line n for chunk 1
FIXED BOUNDARY
Line 1 for chunk 2
Line 2 for chunk 2
...
Line n for chunk 2
FIXED BOUNDARY
Line 1 for chunk 3
...";

List<string[]> parts = text.Split("FIXED BOUNDARY" + Environment.NewLine)
                            .Skip(1)
                            .Select(x => x.Split(Environment.NewLine))
                            .ToList();

"FIXED BOUNDARY" is used as separator and not included in result

Related