有没有更快的方法来检查来自特定索引的 char 数组的子序列是否等于字符串的子序列?
bool Matches (Char[] cs, int i, string s)
{
return cs.Skip(i).Take(s.Length).SequenceEqual(s);
}
假设 cs
和 s
永远不会是 null
。
运行时更快。 我也可以在不创建字符串的新实例的情况下完成吗?因为两者都可以看作是字符数组。
我希望有类似 C's strncmp 的东西
最佳答案
只需使用一个简单的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;
}
关于c# - Char[] 的子序列是否等于字符串的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28795443/