String.Split - 省略空数组元素或低于特定长度

时间:2014-11-24 17:57:27

标签: c#

我知道RemoveEmptyEntries,但是如何让split()也省略小于X字符的元素。

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

伪码:

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

唯一的解决方案是制作循环并删除小于X的循环吗?这有点不高效吗?

1 个答案:

答案 0 :(得分: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)...