有没有更快的方法来检查字符数组的子序列,从特定的索引中是否等于字符串的子序列?
bool Matches (Char[] cs, int i, string s)
{
return cs.Skip(i).Take(s.Length).SequenceEqual(s);
}假设cs和s永远不是null。
在运行时更快。另外,我可以不创建字符串的新实例吗?因为两者都可以看作是char数组。
我希望能有一些类似C's strncmp 的东西
发布于 2015-03-01 23:51:38
只需使用一个简单的for循环。这是为了消除s的边界检查而设计的。
bool Matches (char[] chars, int offset, string s)
{
if(offset < 0)
throw new ArgumentOutOfRangeException("offset");
if(chars.Length - offset < s.Length)
throw new ArgumentException();
for(int i = 0; i < s.Length; i++)
{
if(chars[offset + i] != s[i])
return false;
}
return true;
}发布于 2015-03-02 00:05:18
当然,你也可以自己编写循环,去掉枚举数:
if (cs == null || s == null)
throw new ArgumentNullException();
if (i < 0 || i > cs.Length)
throw new ArgumentException("i");
if (cs.Length - i != s.Length)
return false;
for (int j = 0; j != s.Length; ++j) {
if (s[j] != cs[j + i])
return false;
}
return true;但这仍然不会像调用原生字符串函数那样快,因为它会对每个下标访问进行边界检查(通常这不是什么大问题,但既然你追求的是速度,为什么不全力以赴)。因此,我们可以下拉一个抽象级别并使用指针:
if (cs == null || s == null)
throw new ArgumentNullException();
if (i < 0 || i > cs.Length)
throw new ArgumentException("i");
if (cs.Length - i != s.Length)
return false;
unsafe {
fixed (char* ps = s, pcs_ = cs) {
char* pcs = pcs_ + i;
for (int j = 0; j != s.Length; ++j) {
if (pcs[j] != ps[j])
return false;
}
}
}
return true;https://stackoverflow.com/questions/28795443
复制相似问题