使用Split()时执行Trim() [英] Perform Trim() while using Split()

查看:68
本文介绍了使用Split()时执行Trim()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我想知道是否有更好的解决方案来执行以下代码示例.

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屋!

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