Ullan
Ullan

Reputation: 1007

How to Split a string using the delimiter with quotes and white spaces?

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.

Upvotes: 1

Views: 64

Answers (2)

user2147873
user2147873

Reputation: 107

Just keep only the first line.

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

Upvotes: 3

Klaus Gütter
Klaus Gütter

Reputation: 11977

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.

Upvotes: 2

Related Questions