让我们说我有一个文本,我想找到每个逗号的位置。字符串,一个较短的版本,应该是这样的:
Let's say I have a text and I want to locate the positions of each comma. The string, a shorter version, would look like this:
string s = "A lot, of text, with commas, here and,there";
在理想情况下,我会用这样的:
Ideally, I would use something like:
int[] i = s.indexOf(',');
但因为只的indexOf返回第一个逗号,而不是我做的:
but since indexOf only returns the first comma, I instead do:
List<int> list = new List<int>();
for (int i = 0; i < s.Length; i++)
{
if (s[i] == ',')
list.Add(i);
}
是否有替代,这样做的更优化的方式?
Is there an alternative, more optimized way of doing this?
您可以使用 Regex.Matches(字符串,字符串)方法。这将返回一个MatchCollection,然后你可以决定Match.Index。 MSDN有一个很好的例子,
You could use Regex.Matches(string, string) method. This will return a MatchCollection and then you could determine the Match.Index. MSDN has a good example,
使用系统; 使用System.Text.RegularEx pressions;
using System; using 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