Home >Backend Development >C++ >How Can I Find All Occurrences of a Substring in a String Using C#?
Finding All Positions of a Substring in a Larger String in C#
The task of finding all occurrences of a specific substring within a larger string is a common challenge in programming. In C#, the IndexOf method provides a straightforward approach, yet it fails to capture multiple instances of the substring.
A better alternative is to leverage an extension method. Here's an implementation:
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); } }
To use this extension method, simply import the namespace it resides in and invoke it directly on the string:
List<int> indexes = "fooStringfooBar".AllIndexesOf("foo");
This method efficiently identifies all instances of the substring in the larger string, providing a comprehensive list of their positions.
The above is the detailed content of How Can I Find All Occurrences of a Substring in a String Using C#?. For more information, please follow other related articles on the PHP Chinese website!