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

标签 c# .net asp.net string

我有一个大字符串需要解析,我需要找到 extract"(me,i-have lots.of]punctuation 的所有实例,并将每个实例的索引存储到一个列表。

假设这段字符串位于较大字符串的开头和中间,它们都会被找到,并且它们的索引将被添加到 List 中。 List 将包含 0 和其他索引,无论它是什么。

我一直在玩,string.IndexOf 确实几乎我正在寻找的东西,我已经写了一些代码 - 但它不起作用而且我一直无法弄清楚到底出了什么问题:

List<int> inst = new List<int>();
int index = 0;
while (index < source.LastIndexOf("extract\"(me,i-have lots. of]punctuation", 0) + 39)
{
    int src = source.IndexOf("extract\"(me,i-have lots. of]punctuation", index);
    inst.Add(src);
    index = src + 40;
}
  • inst = 列表
  • source = 大字符串

有什么更好的主意吗?

最佳答案

这是一个扩展方法示例:

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);
    }
}

如果你把它放到一个静态类中并使用 using 导入命名空间,它会在任何字符串上显示为一个方法,你可以这样做:

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

有关扩展方法的更多信息,http://msdn.microsoft.com/en-us/library/bb383977.aspx

同样使用迭代器:

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;
    }
}

关于c# - 在C#中查找较大字符串中子字符串的所有位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2641326/

相关文章:

c# - 提高网站性能 - ASP.NET

c# - 外部注销后如何重定向到设置注销页面(openid Connect)Asp net core 3.1

c# - 一种使用独特压缩形式解压缩文本文件的更快方法

.net - 我可以在 Mono/Linux 上使用 Visual Studio 附带的 FSharp.Core 吗

c# - 在 azure blob 存储中设置 Ionic Zip 密码,并为 zip 文件夹而不是文件设置最佳压缩

c# - 仅在按下左键时捕获鼠标移动事件

c# - Npgsql 奇怪的异常

c# - 在 C# 代码隐藏中修剪字符串

c# - 使用 SendMessage() 最小化所有窗口,但需要比 Thread.Sleep() 更有效的方法来等待旧版桌面显示

c# - Cookie 总是过期