我有一个巨大的字符串(内容页面)我想获取子字符串实例的所有索引。
示例:你好吗,你在哪里?
我如何在上面的句子中获得所有人的索引。
请帮忙。
您可以使用以下扩展。它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;
}
您以这种方式使用它:
string text = " How are you and where are you?";
var allIndexOf = text.AllIndexOf("you", StringComparison.OrdinalIgnoreCase);
Console.WriteLine(string.Join(",", allIndexOf)); // 9,27
StringComparison
允许不区分大小写地搜索。
您可以在循环中使用带有 startIndex 参数的IndexOf 方法,并将其传递last_match_index + 1
给它。
就像是:
int pos=-1, count=0;
while((pos=str.IndexOf("you",pos+1))!=-1)
{
count++;
}
string input = "How are you and where are you?";
var indexes = Regex.Matches(input, "you").Cast<Match>().Select(m => m.Index)
.ToList();