使用Split()时执行Trim() [英] Perform Trim() while using Split()
问题描述
今天我想知道是否有更好的解决方案来执行以下代码示例.
today I was wondering if there is a better solution perform the following code sample.
string keyword = " abc, foo , bar";
string match = "foo";
string[] split= keyword.Split(new char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries);
foreach(string s in split)
{
if(s.Trim() == match){// asjdklasd; break;}
}
有没有一种方法可以执行trim()而无需手动遍历每个项目?我正在寻找类似由以下字符分割并自动修剪每个结果"的内容.
Is there a way to perform trim() without manually iterating through each item? I'm looking for something like 'split by the following chars and automatically trim each result'.
啊,在发帖之前立即找到我
Ah, immediatly before posting I found
List<string> parts = line.Split(';').Select(p => p.Trim()).ToList();
我还是很好奇:也许有更好的解决方案吗?(或者编译器可能会将它们转换为与Linq-Operation相同的代码输出?)
Still I'm curious: Might there be a better solution to this? (Or would the compiler probably convert them to the same code output as the Linq-Operation?)
推荐答案
另一个可能的选择(避免LINQ,无论好坏):
Another possible option (that avoids LINQ, for better or worse):
string line = " abc, foo , bar";
string[] parts= Array.ConvertAll(line.Split(','), p => p.Trim());
但是,如果您只需要知道它是否存在-可能是短路?
However, if you just need to know if it is there - perhaps short-circuit?
bool contains = line.Split(',').Any(p => p.Trim() == match);
这篇关于使用Split()时执行Trim()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!