How to get the Index of second comma in a string

C#.NetStringIndexof

C# Problem Overview


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!

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSem0View Question on Stackoverflow
Solution 1 - C#Logan MurphyView Answer on Stackoverflow
Solution 2 - C#BenVlodgiView Answer on Stackoverflow