0

I think the function IndexOf from class string only can return the first ocurrence of a char in a string.

For example

 string foo="blahblahblah";
 int num=foo.IndexOf("l") would make num= 1.

But I wonder if there's a similar function that would work this way:

 string foo="blahblahblah"
 int indexNumber=2;
 int num=foo.aFunction("l",indexNumber) would make num=5.
 indexNumber=3;
 num=foo.aFunction("l",indexNumber) would make num= 9.

And so on with indexNumber indicating that it shouldn't return the first ocurrence, but the one that it's indicated into it.

Can you guide me about that function or a code to achieve this?

user2638180
  • 1,013
  • 16
  • 37

3 Answers3

2

this extension returns all indexes of a given string

public static IEnumerable<int> AllIndexesOf(this string str, string searchstring)
{
    int minIndex = str.IndexOf(searchstring);
    while (minIndex != -1)
    {
        yield return minIndex;
        minIndex = str.IndexOf(searchstring, minIndex + searchstring.Length);
    }
}

with the following result

string foo = "blahblahblah";
var result = foo.AllIndexesOf("l"); // 1,5,9
fubo
  • 44,811
  • 17
  • 103
  • 137
1

You can call an overload of the indexOf method where you specify the start point for searching:

https://msdn.microsoft.com/en-us/library/7cct0x33%28v=vs.110%29.aspx

So once you've found the first index, if you use that value to start searching from that point to find the next indexOf.

Edit to say this is demonstrated in the code in fubo's answer.

cf_en
  • 1,661
  • 1
  • 10
  • 18
0

You can use regular expressions, Regex.Matches gives a collection of all given substrings:

string foo = "blahblahblah";
MatchCollection matches = Regex.Matches(foo, "l");

foreach (Match m in matches)
    Console.WriteLine(m.Index);
w.b
  • 11,026
  • 5
  • 30
  • 49