在 C# 中查找较大字符串中子字符串的所有位置
查找较大字符串中子字符串的出现位置是一项常见的编程任务。在 C# 中, string.IndexOf() 方法提供了一种查找子字符串第一次出现的便捷方法,但它没有提供查找所有出现的子字符串的直接方法。
要查找子字符串的所有出现,您可以使用循环遍历较大的字符串,同时使用 string.IndexOf() 方法来定位每个匹配项。但是,如果较大的字符串很大并且多次找到子字符串,则这种方法可能效率低下。
更有效的方法是使用扩展方法,它允许您向现有类添加自定义方法。以下是查找字符串中所有出现的子字符串的扩展方法示例:
public static List<int> AllIndexesOf(this string str, string value) { if (String.IsNullOrEmpty(value)) throw new ArgumentException("the string to find may not be empty", "value"); List<int> indexes = new List<int>(); for (int index = 0;; index += value.Length) { index = str.IndexOf(value, index); if (index == -1) return indexes; indexes.Add(index); } }
使用此扩展方法,您可以使用以下语法查找字符串中出现的所有子字符串:
List<int> indexes = "fooStringfooBar".AllIndexesOf("foo");
或者,您也可以使用迭代器来查找 a 的所有出现子字符串:
public static IEnumerable<int> AllIndexesOf(this string str, string value) { if (String.IsNullOrEmpty(value)) throw new ArgumentException("the string to find may not be empty", "value"); for (int index = 0;; index += value.Length) { index = str.IndexOf(value, index); if (index == -1) break; yield return index; } }
此迭代器允许您使用 foreach 语句迭代子字符串的出现次数:
foreach (int index in "fooStringfooBar".AllIndexesOf("foo")) { // do something with the index }
以上是如何高效地查找 C# 字符串中所有出现的子字符串?的详细内容。更多信息请关注PHP中文网其他相关文章!