Equivalent to StringSplitOptions.RemoveEmptyEntries for TextFieldParser

I recently studied TextFieldParser for parsing words , where previously I would use string.Split for this. And I have a question regarding a recently acquired class .

If we parse such a message 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 get words that contain three elements like this:

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

But if we do this 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 return will consist of some words without text

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

Now there is an equivalent way to delete empty words in the resulting array, since string.Split StringSplitOptions.RemoveEmptyEntries does?

+2
c # parsing textfieldparser
source share
1 answer

Maybe it will be a trick

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

One liner Alternative may be

 string[] words2 = parser.ReadFields().Where(x => !string.IsNullOrEmpty(x)).ToArray(); 
+1
source share

All Articles