2014-11-24 82 views
-2

我知道RemoveEmptyEntries,但是如何使split()也省略小于X字符的元素。String.Split - 省略空数组元素或低于一定的长度

string s = "test:tessss:t:pas"; 

伪代码:

s.Split(':', 2, StringSplitOptions.RemoveEmptyEntries); 
//Where 2 is the minimum length to not be omitted. 

是使循环,去除那些小于X唯一的解决办法?这不是没有效率吗?

+2

是什么使得它效率低下?听起来像是对我来说非常好的解决方案。 – tnw 2014-11-24 17:58:47

+2

确实有可能编写一个专用方法,该方法仅返回比最初分割然后过滤的解决方案快的最小长度以上的部分。但是,这个特定操作成为代码中的瓶颈(因此甚至值得优化)的机会很小,所以不要为此付出代价。 – 2014-11-24 18:03:19

回答

4
var minLength = 2; 
var entriesArr = s.Split(':', StringSplitOptions.RemoveEmptyEntries) 
.Where(s => s.Length >= minLength) 
.ToArray(); 

种使StringSplitOptions.RemoveEmptyEntries多余的使用。

你可以做一个扩展方法:

public static class StringEx 
{ 
    public static string[] Split(this string s, char sep, int minLength) 
    { 
     return s.Split(sep) 
       .Where(s => s.Length >= minLength) 
       .ToArray(); 
    } 
} 

,那么你可以:

var str = "bar b foo"; 
str.Split(' ', 2)...