IndexOf
,IndexOfAny
和LastIndexOf
,LastIndexOfAny
似乎没有执行这些操作(或者也许是这样做的)。我正在寻找std::string的find_first_not_of
和find_last_not_of
的等效项。我正在考虑创建扩展类,但不确定C#是否已提供此功能。
最佳答案
string source = "the quick brown fox jumps over the lazy dog";
string chars = "ogd hte";
int? firstNotOf = source.Select((x, i) => new { Val = x, Idx = (int?)i })
.Where(x => chars.IndexOf(x.Val) == -1)
.Select(x => x.Idx)
.FirstOrDefault();
int? lastNotOf = source.Select((x, i) => new { Val = x, Idx = (int?)i })
.Where(x => chars.IndexOf(x.Val) == -1)
.Select(x => x.Idx)
.LastOrDefault();
或者,如果您更喜欢一些非LINQ扩展方法。这些应该有更好的性能,尤其是对于
FindLastNotOf
:int? firstNotOf = source.FindFirstNotOf(chars);
int? lastNotof = source.FindLastNotOf(chars);
// ...
public static int? FindFirstNotOf(this string source, string chars)
{
if (source == null) throw new ArgumentNullException("source");
if (chars == null) throw new ArgumentNullException("chars");
if (source.Length == 0) return null;
if (chars.Length == 0) return 0;
for (int i = 0; i < source.Length; i++)
{
if (chars.IndexOf(source[i]) == -1) return i;
}
return null;
}
public static int? FindLastNotOf(this string source, string chars)
{
if (source == null) throw new ArgumentNullException("source");
if (chars == null) throw new ArgumentNullException("chars");
if (source.Length == 0) return null;
if (chars.Length == 0) return source.Length - 1;
for (int i = source.Length - 1; i >= 0; i--)
{
if (chars.IndexOf(source[i]) == -1) return i;
}
return null;
}
(在LINQ和非LINQ版本中,如果将
chars
转换为HashSet<char>
或什至是简单的char[]
数组,都有可能获得更好的性能。除非chars
变得很大,否则差异可能可以忽略不计。)关于相当于C++ std::string find_first_not_of和find_last_not_of的C#,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4498176/