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

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

问题描述

我有一个大字符串需要解析,我需要找到所有 extract(我,我有很多标点符号的实例,以及

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 =列表

  • =大字符串

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

      如果将其放入静态类并导入带有使用的名称空间,它作为任何字符串上的方法出现,您可以执行以下操作:

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