Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the Index of second comma in a string

People also ask

How do you find the index of a string character?

To get the index of a character in a string, you use the indexOf() method, passing it the specific character as a parameter. This method returns the index of the first occurrence of the character or -1 if the character is not found. Copied!

How do you find second occurrence of a character in a string in VB net?

Answers. You've declared charToFind as Char but then pass a String value to the method. If you put Option Strict On at the top of your code you would have an error on your call of GetNthIndex(). I believe this is used with arrays "searchString.

Can you index strings in C#?

In C#, IndexOf() method is a string method. This method is used to find the zero-based index of the first occurrence of a specified character or string within the current instance of the string. The method returns -1 if the character or string is not found.


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.


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