Question

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(',')));
Was it helpful?

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;
}

OTHER TIPS

Just specify which character do you want and which occurance in next parameter

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

Here is your solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top