在 C# 中查找较大字符串中子字符串的所有位置 [英] Finding all positions of substring in a larger string in C#

查看:42
本文介绍了在 C# 中查找较大字符串中子字符串的所有位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a large string I need to parse, and I need to find all the instances of extract"(me,i-have lots. of]punctuation, and store the index of each to a list.

所以说这段字符串在较大字符串的开头和中间,两者都会被找到,并且它们的索引会被添加到List中.并且 List 将包含 0 和其他索引,无论它是什么.

So say this piece of string was in the beginning and middle of the larger string, both of them would be found, and their indexes would be added to the List. and the List would contain 0 and the other index whatever it would be.

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

I've been playing around, and the string.IndexOf does almost what I'm looking for, and I've written some code - but it's not working and I've been unable to figure out exactly what is wrong:

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 = 大字符串
    • inst = The list
    • source = The large string
    • 有更好的想法吗?

      推荐答案

      这是它的扩展方法示例:

      Here's an example extension method for it:

      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导入命名空间,它会在任何字符串上显示为一个方法,你可以这样做:

      If you put this into a static class and import the namespace with using, it appears as a method on any string, and you can just do:

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

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

      For more information on extension methods, 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# 中查找较大字符串中子字符串的所有位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆