问题
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:
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();
来源:https://stackoverflow.com/questions/34624536/stringsplitoptions-removeemptyentries-equivalent-for-textfieldparser