Home > database >  Easier method to group by multiple newlines
Easier method to group by multiple newlines

Time:12-06

Today I've faced a problem that looked easy at glance but it was not certainly as simple. My task is to group multiple strings separated by two newlines. Example:

a
b

c
d

e
f
g

h

into:

[ [a, b], [c, d], [e, f, g], [h] ]

At first I thought about getting the groups out of a regular expression, but I couldn't find the right one to separate and give me the strings grouped. Then I decided to look at it with LINQ, but I couldn't manage to get anything useful either. Any tips?

CodePudding user response:

You can use String.Split with two concatenated Environment.NewLine:

string[][] result = text.Split(new [] { Environment.NewLine   Environment.NewLine }, StringSplitOptions.None)
    .Select(token => token.Split(new []{Environment.NewLine}, StringSplitOptions.None))
    .ToArray();

https://dotnetfiddle.net/NinneE

CodePudding user response:

Splitting input by new line is a classic from AOC. Here is a part of my extention Method .net 7:


public static class Extention{
  /// <summary>
  /// Splits a text into lines.
  /// </summary>
  public static IEnumerable<string> Lines(this string text) => text.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries);

  /// <summary>
  /// Splits a text into blocks of lines. Split occurs on each empty line.
  /// </summary>
  public static IEnumerable<string> Blocks(this string text) => text.Trim().Split(Environment.NewLine   Environment.NewLine, StringSplitOptions.RemoveEmptyEntries);
}

Code will be :

var result = text.Blocks()
                 .Select(b => b.Lines());

NB:
.Split(Environment.NewLine Environment.NewLine, is .NET 7

  • Related