Home > front end >  How to Split a string using the delimiter with quotes and white spaces?
How to Split a string using the delimiter with quotes and white spaces?

Time:05-17

I want to split a string using only the delimiter. But my code is breaking if the string has white spaces.

1233;"Order";Placed at 10 AM;1

When I split it, the out put is

1233
\"Order"\
Placed 
at
10
AM
1

Expected output is:

1233
\"Order"\
Placed at 10 AM
1

My Code:

                    var result = columns[0].Split(';')
                 .Select((element, index) => index % 2 == 0  
                  ? element.Split(new[] { ' ' }, StringSplitOptions.None)                                             : new string[] { element })  // Keep the entire item
                 .SelectMany(element => element).ToList();

Thanks for fixing this issue.

CodePudding user response:

Just keep only the first line.

var result = columns[0].Split(';');

CodePudding user response:

You are explicitely also splitting on spaces: Split(new[] { ' ' }.

If you only want to split on semicolons, this is sufficient:

var result = columns[0].Split(';');

You might also consider using a library like CsvHelper.

  • Related