首頁 > 後端開發 > C++ > 如何有效率地查找 C# 字串中所有出現的子字串?

如何有效率地查找 C# 字串中所有出現的子字串?

Susan Sarandon
發布: 2025-01-01 12:36:10
原創
978 人瀏覽過

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
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板