StringSplitOptions.RemoveEmptyEntries equivalent for TextFieldParser

非 Y 不嫁゛ 提交于 2019-12-12 20:06:59

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!