首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在C#中查找较大字符串中子字符串的所有位置

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

Stack Overflow用户
提问于 2010-04-15 05:52:48
回答 14查看 117.1K关注 0票数 89

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

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

我一直在尝试,string.IndexOf几乎完成了我正在寻找的东西,我写了一些代码-但它不能工作,我无法找出到底是哪里出了问题:

代码语言:javascript
复制
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

有更好的主意吗?

EN

回答 14

Stack Overflow用户

回答已采纳

发布于 2010-04-15 06:04:02

下面是它的一个示例扩展方法:

代码语言:javascript
复制
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导入名称空间,则它将显示为任何字符串上的方法,您只需执行以下操作:

代码语言:javascript
复制
List<int> indexes = "fooStringfooBar".AllIndexesOf("foo");

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

使用迭代器也是一样的:

代码语言:javascript
复制
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;
    }
}
票数 151
EN

Stack Overflow用户

发布于 2010-04-15 09:04:31

为什么不使用内置的RegEx类:

代码语言:javascript
复制
public static IEnumerable<int> GetAllIndexes(this string source, string matchString)
{
   matchString = Regex.Escape(matchString);
   foreach (Match match in Regex.Matches(source, matchString))
   {
      yield return match.Index;
   }
}

如果您确实需要重用表达式,那么编译它并将其缓存到某个地方。对于重用情况,在另一个重载中将matchString参数更改为正则表达式matchExpression。

票数 24
EN

Stack Overflow用户

发布于 2010-04-15 10:38:54

使用LINQ

代码语言:javascript
复制
public static IEnumerable<int> IndexOfAll(this string sourceString, string subString)
{
    return Regex.Matches(sourceString, subString).Cast<Match>().Select(m => m.Index);
}
票数 15
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2641326

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档