-1

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(',')));
Alex K.
  • 171,639
  • 30
  • 264
  • 288
user3560486
  • 27
  • 1
  • 4
  • 1
    Assuming C# ; [C# - indexOf the nth occurrence of a string?](http://stackoverflow.com/questions/186653/c-sharp-indexof-the-nth-occurrence-of-a-string) – Alex K. May 13 '14 at 14:24

2 Answers2

0

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

Laxmikant Dange
  • 7,606
  • 6
  • 40
  • 65
  • you didn't understand me. I have "Something1, something2, something3, something4. And I want "something3". – user3560486 May 13 '14 at 14:42
  • your starting point for substring is 0 so it will trim string from 0th position – Laxmikant Dange May 13 '14 at 14:49
  • 1
    That `int` parameter to `IndexOf` [is the index to start at, not the occurrence number](http://msdn.microsoft.com/en-us/library/5xkyx09y.aspx). – Rawling May 13 '14 at 14:49
  • 1
    Hmm, don't like this "I want" attitude. We're here to help, but when expectations are that we're in any way obligated to write code for you, that does make me feel a little uncomfortable. – TEK May 13 '14 at 15:10
0

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;
}
Laxmikant Dange
  • 7,606
  • 6
  • 40
  • 65