hattenn
hattenn

Reputation: 4399

How to split a string two times with different separators using LINQ?

I have strings like "1\t2\r\n3\t4" and I'd like to split them as:

new string[][] { { 1, 2 }, { 3, 4 } }

Basically, it should be split into lines, and each line should be split into tabs. I tried using the following, but it doesn't work:

string toParse = "1\t2\r\n3\t4";

string[][] parsed = toParse
    .Split(new string[] {@"\r\n"}, StringSplitOptions.None)
    .Select(s => s.Split('\t'))
    .ToArray();
  1. What is wrong with my method? Why don't I get the desired result?
  2. How would you approach this problem using LINQ?

Upvotes: 5

Views: 2053

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460068

string str = "1\t2\r\n3\t4";
Int32[][] result = str.Split(new[] { Environment.NewLine }, StringSplitOptions.None)
    .Select(s => s.Split('\t').Select(s2 => int.Parse(s2)).ToArray())
    .ToArray();

Demo

Upvotes: 3

TheEvilPenguin
TheEvilPenguin

Reputation: 5672

Remove the '@':

string toParse = "1\t2\r\n3\t4";

string[][] parsed = toParse
    .Split(new string[] {"\r\n"}, StringSplitOptions.None)
    .Select(s => s.Split('\t'))
    .ToArray();

The @ makes the string include the backslashes, instead of the character they represent.

Upvotes: 7

Related Questions