您可以使用以下扩展名。它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可以搜索不区分大小写。
您可以在循环中使用带有 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)
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)
| 归档时间: |
|
| 查看次数: |
6658 次 |
| 最近记录: |