Jon*_*eet 16
这个扩展方法怎么样:
public static IEnumerable<int> 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;
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,在"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;
}
Run Code Online (Sandbox Code Playgroud)
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<int>();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7493 次 |
| 最近记录: |