.indexOf用于多个结果

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

string s = "A lot, of text, with commas, here and,there"; 

理想情况下,我会使用类似的东西:

 int[] i = s.indexOf(','); 

但由于indexOf只返回第一个逗号,我改为:

 List list = new List(); 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 = @"\b\w+es\b"; 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 

在这里我有一个扩展:

 public static IEnumerable 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(","); 

IndexOf还允许您添加另一个参数以便从哪里开始查找 。 您可以将该参数设置为最后一个已知的逗号位置+1。 例如:

 string s = "A lot, of text, with commas, here and, there"; int loc = s.IndexOf(','); while (loc != -1) { Console.WriteLine(loc); loc = s.IndexOf(',', loc + 1); } 

您可以使用IndexOf方法的重载,该方法也使用起始索引来获取以下逗号,但您仍然必须在循环中执行此操作,并且它将执行与您拥有的代码几乎相同的操作。

您可以使用正则表达式来查找所有逗号,但这会产生相当大的开销,因此不会比您拥有的更优化。

您可以编写一个LINQ查询来以不同的方式执行它,但这也有一些开销,因此它不会比您拥有的更优化。

因此,有许多替代方法,但不是任何更优化的方式。