60

I have a string in an Array that contains two commas as well as tabs and white spaces. I'm trying to cut two words in that string, both of them before the commas, I really don't care about the tabs and white spaces.

My String looks similar to this:

String s = "Address1       Chicago,  IL       Address2     Detroit, MI"

I get the index of the first comma

int x = s.IndexOf(',');

And from there, I cut the string before the index of the first comma.

firstCity = s.Substring(x-10, x).Trim() //trim white spaces before the letter C;

So, how do I get the index of the second comma so I can get my second string?

I really appreciate your help!

Ghasem
  • 14,455
  • 21
  • 138
  • 171
Sem0
  • 603
  • 1
  • 5
  • 6

3 Answers3

115

You have to use code like this.

int index = s.IndexOf(',', s.IndexOf(',') + 1);

You may need to make sure you do not go outside the bounds of the string though. I will leave that part up to you.

Logan Murphy
  • 6,120
  • 3
  • 24
  • 42
69

I just wrote this Extension method, so you can get the nth index of any sub-string in a string.

Note: To get the index of the first instance, use nth = 0.

public static class Extensions
{
    public static int IndexOfNth(this string str, string value, int nth = 0)
    {
        if (nth < 0)
            throw new ArgumentException("Can not find a negative index of substring in string. Must start with 0");
        
        int offset = str.IndexOf(value);
        for (int i = 0; i < nth; i++)
        {
            if (offset == -1) return -1;
            offset = str.IndexOf(value, offset + 1);
        }
        
        return offset;
    }
}
BenVlodgi
  • 2,135
  • 1
  • 13
  • 26
-1

LastIndexOf gives you the Index of the last occurence of the given char / string.

int index = s.LastIndexOf(',');
BlyZe
  • 43
  • 1
  • 10
  • Kindly add more details to your answer, explanations on how your code works and how this address the OP's question would be a great help not just for the asker but also for the future researchers. – Kuro Neko May 31 '22 at 05:49
  • this is not the second but the last – Paramar Jun 15 '22 at 14:54