2

我最近学会TextFieldParser了解析words以前我会string.Split用来做的地方。我有一个关于新学到的问题class

如果我们使用string.Splitwith解析这样的消息StringSplitOptions.RemoveEmptyEntries

string message = "create    myclass   \"56, 'for better or worse'\""; //have multiple spaces
string[] words = message.Split(new char[] { ' ' }, 3, StringSplitOptions.RemoveEmptyEntries);

然后我们将得到words其中包含三个元素,如下所示:

[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没有文字的

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

现在有没有等效的方法来删除words结果数组中的空string.Split StringSplitOptions.RemoveEmptyEntries

4

1 回答 1

1

可能这会成功

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();
于 2016-01-06T02:15:35.987 回答