StringSplitOptions.RemoveEmptyEntries equivalent f

2019-07-09 04:37发布

I recently learn TextFieldParser to parse words where previously I would use string.Split to do so. And I have a question regarding the newly learned class.

If we parse a message like this using string.Split with StringSplitOptions.RemoveEmptyEntries

string message = "create    myclass   \"56, 'for better or worse'\""; //have multiple spaces
string[] words = message.Split(new char[] { ' ' }, 3, StringSplitOptions.RemoveEmptyEntries);

Then we will get words which contain three elements like this:

[0] create
[1] myclass
[2] "56, 'for better or worse'"

But if we do it with TextFieldParser

string str = "create    myclass   \"56, 'for the better or worse'\"";
var parser = new Microsoft.VisualBasic.FileIO.TextFieldParser(new StringReader(str)); //treat string as I/O
parser.Delimiters = new string[] { " " };
parser.HasFieldsEnclosedInQuotes = true; 
string[] words2 = parser.ReadFields();

Then the return will consists of some words without text

[0] create
[1]
[2]
[3]
[4] myclass
[5]
[6]
[7] "56, 'for better or worse'"

Now is there equivalent way to remove the empty words in the resulting array as string.Split StringSplitOptions.RemoveEmptyEntries does?

1条回答
Fickle 薄情
2楼-- · 2019-07-09 05:11

May be this would do the trick

parser.HasFieldsEnclosedInQuotes = true;
string[] words2 = parser.ReadFields();
words2 = words2.Where(x => !string.IsNullOrEmpty(x)).ToArray();

One liner Alternative could be

string[] words2 = parser.ReadFields().Where(x => !string.IsNullOrEmpty(x)).ToArray();
查看更多
登录 后发表回答