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

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

DDD
DDDOriginal
2025-01-04 03:36:40338browse

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!

Statement:
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