Home > Backend Development > C++ > How Can I Find All Occurrences of a Substring Within a String in C#?

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

Susan Sarandon
Release: 2024-12-30 01:59:08
Original
364 people have browsed it

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

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
}
Copy after login

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;
    }
}
Copy after login

Using this extension method, you can easily find all occurrences of a substring as follows:

List<int> indexes = "fooStringfooBar".AllIndexesOf("foo");
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template