Finding All Positions of a Substring Within a Larger String in C#
Problem:
Given a large string, you need to identify and store the positions of all occurrences of a specified substring within that string. For instance, if the substring is "extract"(me,i-have lots. of]punctuation" appears at the beginning and middle of the larger string, both instances should be located and their index positions added to a list, resulting in a list containing 0 and the index of the middle occurrence.
Solution:
The provided code utilizes the IndexOf method, which can be used to locate the first occurrence of a substring within a string. However, this method only returns the first match. To find all occurrences, a loop can be employed to repeatedly call IndexOf starting from the position after the previous match until no further matches are found. The index positions can then be added to the desired list.
Here's a corrected version of the provided code:
List<int> inst = new List<int>(); int index = 0; while (index < source.Length) { int src = source.IndexOf("extract\"(me,i-have lots. of]punctuation", index); if (src == -1) break; // No more occurrences found inst.Add(src); index = src + 40; // Advance the search index to beyond the current match }
Alternative Approaches:
Another solution involves using an extension method for greater convenience. Here's an example extension method that leverages the iterator pattern:
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; } }
Using this extension method, you can easily find all occurrences of a substring as follows:
List<int> indexes = "fooStringfooBar".AllIndexesOf("foo");
The above is the detailed content of How Can I Find All Occurrences of a Substring Within a String in C#?. For more information, please follow other related articles on the PHP Chinese website!