我知道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的循环吗?这有点不高效吗?
答案 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)...