首页 >后端开发 >C++ >如何高效地查找 C# 字符串中所有出现的子字符串?

如何高效地查找 C# 字符串中所有出现的子字符串?

Susan Sarandon
Susan Sarandon原创
2025-01-01 12:36:10975浏览

How Can I Efficiently Find All Occurrences of a Substring in a C# String?

在 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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn