假设我有一个文本,我想找到每个逗号的位置。该字符串(较短的版本)如下所示:
string s = "A lot, of text, with commas, here and,there";
理想情况下,我会使用如下内容:
int[] i = s.indexOf(',');
但是因为 indexOf 只返回第一个逗号,所以我改为:
List<int> list = new List<int>();
for (int i = 0; i < s.Length; i++)
{
if (s[i] == ',')
list.Add(i);
}
有没有更优化的替代方法?
最佳答案
这里我得到了一个扩展方法,与 IndexOf
的用途相同:
public static IEnumerable<int> AllIndexesOf(this string str, string searchstring)
{
int minIndex = str.IndexOf(searchstring);
while (minIndex != -1)
{
yield return minIndex;
minIndex = str.IndexOf(searchstring, minIndex + searchstring.Length);
}
}
所以你可以使用
s.AllIndexesOf(","); // 5 14 27 37
关于c# - .indexOf 用于多个结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6865419/