使用方便的扩展
IEnumerable
看起来应该已经有了,你可以写一个
String
扩展以使用
StringComparer
.正如注释中所建议的,所有可能的子串长度都在每个位置进行测试,因为没有关于自定义的假设
字符串比较器
可以制作。
public static class IEnumerableExt {
public static T FirstOrDefault<T>(this IEnumerable<T> src, Func<T, bool> testFn, T defval) => src.Where(aT => testFn(aT)).DefaultIfEmpty(defval).First();
}
public static class StringExt {
public static int IndexOf(this string source, string match, StringComparer sc) {
return Enumerable.Range(0, source.Length) // for each position in the string
.FirstOrDefault(i => // find the first position where either
// match is Equal at this position for length of match (or to end of string) or
sc.Equals(source.Substring(i, Math.Min(match.Length, source.Length-i)), match) ||
// match is Equal to one of the substrings beginning at this position
Enumerable.Range(1, source.Length-i).Any(ml => sc.Equals(source.Substring(i, ml), match)),
-1 // else return -1 if no position matches
);
}
}
注意:修改为在源子字符串和匹配字符串长度可能不相等时正确处理。