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