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

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

我一直在玩,string.IndexOf做了我想要的almost,我写了一些代码-但它不起作用,我也不能准确地找出哪里出了问题:

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

Asp.net相关问答推荐

InvalidOperationException:在程序集上找不到UserSecretsIdAttribute

如何向 Array.IndexOf 添加不区分大小写的选项

指定的 CGI 应用程序遇到错误,服务器终止了进程

判断 asp.net mvc 4 应用程序中的 ssl 协议、密码和其他属性

如何通过 Asp.net 中的命令参数传递多个值?

在控制器 asp.net mvc 5 的视图上显示错误消息

我可以在 Visual Studio 2010 中将任务列表项添加到 csHTML 吗?

ASP.NET MVC 中的 ASP.NET AJAX 与 jQuery

这两种方法有什么区别?

使用 ASP.NET WebForms 的 jQuery DataTables 服务器端处理

如何在 ASP.NET MVC3 中配置区域

尽管安装了 AspNetCoreModule,但在 IIS 中运行 ASP.NET Core 应用程序时出现 0x8007000d 错误 500.19

@(at) 登录文件路径/字符串

HttpContext.Current 在 MVC 4 项目中未解决

Asp.Net Mvc - 如何在共享视图中有一个控制器

C# - 将图像输出到响应输出流给出 GDI+ 错误

如何告诉 RadioButtonList 不生成表格

如何将代码中的变量调用到aspx页面

为什么 IFormFile 显示为空,我该如何解决?

如何在不遍历每个循环的情况下从字典对象中获取所有键(仅键)