c# - .indexOf 用于多个结果

标签 c# .net

假设我有一个文本,我想找到每个逗号的位置。该字符串(较短的版本)如下所示:

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

https://dotnetfiddle.net/DZdQ0L

关于c# - .indexOf 用于多个结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6865419/

相关文章:

c# - 无法实现撤消/重做功能,我应该使用 Stack 吗?

c# - 调用批处理文件后服务在 WaitForExit 处挂起

c# - 如果方法对引用类型执行操作,是否需要返回它?

.net - 冒充其他用户时发生灾难性失败

c# - 如何保存到外部配置文件

.net - 使用 LocalFileSettingsProvider 进行漫游设置

.net - 如何使用 LINQ 将两个 Sum 操作合二为一?

c# - 如何在 C# ASP.Net 中使用加密密码作为参数

c# - 如何在 WinCE Compact Framework 3.5 中标记用户控件的默认事件

.net - EF 代码首先插入多行