首页 >后端开发 >C++ >如何使用 C# 查找字符串中子字符串的所有出现位置?

如何使用 C# 查找字符串中子字符串的所有出现位置?

DDD
DDD原创
2025-01-04 03:36:40364浏览

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

在 C# 中查找较大字符串中子字符串的所有位置

查找较大字符串中特定子字符串的所有出现的任务是编程中常见的挑战。在 C# 中,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");

此方法有效地识别较大字符串中的子字符串,提供其位置的完整列表。

以上是如何使用 C# 查找字符串中子字符串的所有出现位置?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn