How to get the Index of second comma in a string

Sem0 picture Sem0 · Mar 26, 2014 · Viewed 75.1k times · Source

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!

Answer

Logan Murphy picture Logan Murphy · Mar 26, 2014

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.