How to get the Index of second comma in a string

一世执手 提交于 2019-12-12 07:39:03

问题


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!


回答1:


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.




回答2:


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

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

Note: In this implementation I use 1 = first, instead of a 0 based index. This can easily be changed to use 0 = first, by adding a nth++; to the beginning, and changing the error message for clarity.



来源:https://stackoverflow.com/questions/22669044/how-to-get-the-index-of-second-comma-in-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!