与TextFieldParser等效的StringSplitOptions.RemoveEmptyEntries [英] StringSplitOptions.RemoveEmptyEntries equivalent for TextFieldParser
问题描述
我最近学习了TextFieldParser
来解析words
,以前我会使用string.Split
来解析.我有一个关于新学到的class
的问题.
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
.
如果我们使用string.Split
和StringSplitOptions.RemoveEmptyEntries
string message = "create myclass \"56, 'for better or worse'\""; //have multiple spaces
string[] words = message.Split(new char[] { ' ' }, 3, StringSplitOptions.RemoveEmptyEntries);
然后我们将获得words
,其中包含三个元素,如下所示:
Then we will get words
which contain three elements like this:
[0] create
[1] myclass
[2] "56, 'for better or worse'"
但是如果我们使用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();
然后return
将由一些没有文本的words
组成
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'"
现在有什么等效方法可以像string.Split
StringSplitOptions.RemoveEmptyEntries
一样删除结果数组中的空words
吗?
Now is there equivalent way to remove the empty words
in the resulting array as string.Split
StringSplitOptions.RemoveEmptyEntries
does?
推荐答案
也许可以解决问题
parser.HasFieldsEnclosedInQuotes = true;
string[] words2 = parser.ReadFields();
words2 = words2.Where(x => !string.IsNullOrEmpty(x)).ToArray();
一个班轮替代品可能是
string[] words2 = parser.ReadFields().Where(x => !string.IsNullOrEmpty(x)).ToArray();
这篇关于与TextFieldParser等效的StringSplitOptions.RemoveEmptyEntries的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!