如何在另一个字符串C#中获取字符串的所有IndexOf实例

Ram*_*Ram 2 .net c#

我有一个巨大的字符串(内容页面),我想获取子字符串实例的所有索引。

示例:好吗?在哪里?

我如何获得上面句子中所有的索引。

请帮忙。

Tim*_*ter 6

您可以使用以下扩展名。它IndexOf在带有重载的循环中使用,它允许传递要开始搜索的索引。循环直到它返回-1并将找到的索引添加到集合中:

public static IList<int> AllIndexOf(this string text, string str, StringComparison comparisonType)
{
    IList<int> allIndexOf = new List<int>();
    int index = text.IndexOf(str, comparisonType);
    while(index != -1)
    {
        allIndexOf.Add(index);
        index = text.IndexOf(str, index + 1, comparisonType);
    }
    return allIndexOf;
}
Run Code Online (Sandbox Code Playgroud)

您以这种方式使用它:

string text = " How are you and where are you?";
var allIndexOf = text.AllIndexOf("you", StringComparison.OrdinalIgnoreCase);
Console.WriteLine(string.Join(",", allIndexOf));  // 9,27
Run Code Online (Sandbox Code Playgroud)

StringComparison可以搜索不区分大小写。


ale*_*lex 5

您可以在循环中使用带有 startIndex 参数的IndexOf 方法,并将last_match_index + 1其传递给它。

就像是:

int pos=-1, count=0;

while((pos=str.IndexOf("you",pos+1))!=-1)
{
   count++;
}
Run Code Online (Sandbox Code Playgroud)


I4V*_*I4V 5

string input = "How are you and where are you?";
var indexes = Regex.Matches(input, "you").Cast<Match>().Select(m => m.Index)
                   .ToList();
Run Code Online (Sandbox Code Playgroud)