How to split a string twice into different delimiters using LINQ?

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

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

Basically, it should be split into rows, and each row should be tabbed. I tried using the following, but it does not work:

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

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

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();

In @, the string includes a backslash instead of the character that they represent.

+7
source
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

+3
source

All Articles