加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – .indexOf用于多个结果

发布时间:2020-12-15 20:46:13 所属栏目:百科 来源:网络整理
导读:假设我有一个文本,我想找到每个逗号的位置.字符串是一个较短的版本,如下所示: string s = "A lot,of text,with commas,here and,there"; 理想情况下,我会使用类似的东西: int[] i = s.indexOf(','); 但由于indexOf只返回第一个逗号,我改为: Listint list
假设我有一个文本,我想找到每个逗号的位置.字符串是一个较短的版本,如下所示:

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);
}

是否有另一种更优化的方法?

解决方法

你可以使用 Regex.Matches(string,string)方法.这将返回MatchCollection,然后您可以确定Match.Index. MSDN有一个很好的例子,

使用系统;
使用System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = @"bw+esb";
      string sentence = "Who writes these notes?";

      foreach (Match match in Regex.Matches(sentence,pattern))
         Console.WriteLine("Found '{0}' at position {1}",match.Value,match.Index);
   }
}
// The example displays the following output:
//       Found 'writes' at position 4
//       Found 'notes' at position 17

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读