从源字符串中查找多个索引

基本上我需要做String.IndexOf(),我需要从源字符串中获取索引数组。

有没有简单的方法来获取索引数组?

在提出这个问题之前,我已经搜索了很多,但还没有找到解决这个简单问题的简单解决方案。

var indexs = "Prashant".MultipleIndex('a'); //Extension Method's Class public static class Extensions { static int i = 0; public static int[] MultipleIndex(this string StringValue, char chChar) { var indexs = from rgChar in StringValue where rgChar == chChar && i != StringValue.IndexOf(rgChar, i + 1) select new { Index = StringValue.IndexOf(rgChar, i + 1), Increament = (i = i + StringValue.IndexOf(rgChar)) }; i = 0; return indexs.Select(p => p.Index).ToArray(); } } 

这个扩展方法怎么样:

 public static IEnumerable IndexesOf(this string haystack, string needle) { int lastIndex = 0; while (true) { int index = haystack.IndexOf(needle, lastIndex); if (index == -1) { yield break; } yield return index; lastIndex = index + needle.Length; } } 

请注意,在“XAAAY”中查找“AA”时,此代码现在只会产生1。

如果你真的需要一个数组,请在结果上调用ToArray() 。 (这假设是.NET 3.5,因此支持LINQ。)

我怀疑你必须循环:

  int start = 0; string s = "abcdeafghaji"; int index; while ((index = s.IndexOf('a', start)) >= 0) { Console.WriteLine(index); start = index + 1; } 

使用利用正则表达式的解决方案可能更可靠,使用indexOf函数可能不可靠。 它将找到所有匹配和索引,而不匹配可能导致意外结果的精确短语。 此function通过使用Regex库解决了这个问题。

 public static IEnumerable IndexesOf(string haystack, string needle) { Regex r = new Regex("\\b(" + needle + ")\\b"); MatchCollection m = r.Matches(haystack); return from Match o in m select o.Index; }