与TextFieldParser等效的StringSplitOptions.RemoveEmptyEntries [英] StringSplitOptions.RemoveEmptyEntries equivalent for TextFieldParser

查看:118
本文介绍了与TextFieldParser等效的StringSplitOptions.RemoveEmptyEntries的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近学习了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.SplitStringSplitOptions.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆