Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

split

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?
like image 816
hattenn Avatar asked Feb 10 '13 21:02

hattenn


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

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

like image 185
TheEvilPenguin Avatar answered Nov 14 '22 22:11

TheEvilPenguin


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

like image 43
Tim Schmelter Avatar answered Nov 14 '22 21:11

Tim Schmelter