Search code examples
c#stringsubstringstreamreader

Get index of next same character


I have a file like this: "Something, something, something, something, something"

And I want to get the index of third "," with:

StreamReader sr=new StreamReader("File.txt");
string s=sr.Readline();    
string c=s.Substring(0, s.IndexOf(',')));

Solution

  • Sorry for previous answer, I created a function for you, try this, You need to pass your string, character to find and occurance number as parameters. Here is a demo.

    public static int getSpecifiedIndexOf(string str,char ch,int index)
    {
        int i = 0,o=1;
        while ((i = str.IndexOf(ch, i)) != -1)
        {
            if(o==index)return i;
            o++;
            i++;
        }
        return 0;
    }