发现在一个大的字符串在C#中的子字符串的所有位置 [英] Finding ALL positions of a substring in a large string in C#

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

问题描述

我有一个大的字符串,我需要解析,我需要找到的所有实例提取(我,我,有很多。中]标点符号,和将它们存储到列表。

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 them to a 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 并的几乎的我在寻找的东西,我已经写了一些code。但我似乎无法得到它的工作:

I've been playing around, and the string.IndexOf does almost what I'm looking for, and I've written some code. But I can't seem to get it to work:

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 = The list
    • source = The large string
    • 更好的想法?

      推荐答案

      我很无聊,所以我写了这个扩展方法。这是未经测试,但应该给你一个良好的开端。

      I was bored so I wrote this extension method. It's untested but should give you a good start.

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

      如果你把它变成静态类,并使用与导入,它表现为在任何字符串的方法,你可以这样做:

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

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

      有关扩展方法的更多信息,<一个href="http://msdn.microsoft.com/en-us/library/bb383977.aspx">http://msdn.microsoft.com/en-us/library/bb383977.aspx

      For more information on extension methods, http://msdn.microsoft.com/en-us/library/bb383977.aspx

      编辑:和同样使用迭代器:

      and the same using an iterator:

      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天全站免登陆