如何获取字符串中第二个逗号的索引

Sem*_*em0 33 .net c# string indexof

我在一个数组中有一个字符串,其中包含两个逗号以及制表符和空格.我试图在字符串中剪切两个单词,两个单词都在逗号之前,我真的不关心标签和空格.

我的String看起来与此类似:

String s = "Address1       Chicago,  IL       Address2     Detroit, MI"
Run Code Online (Sandbox Code Playgroud)

我得到了第一个逗号的索引

int x = s.IndexOf(',');
Run Code Online (Sandbox Code Playgroud)

从那里,我在第一个逗号的索引之前剪切了字符串.

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

那么,我如何获得第二个逗号的索引,以便获得第二个字符串?

我真的很感谢你的帮助!

Log*_*phy 76

你必须使用这样的代码.

int index = s.IndexOf(',', s.IndexOf(',') + 1);
Run Code Online (Sandbox Code Playgroud)

您可能需要确保不要超出字符串的范围.我会把那部分留给你.


Ben*_*dgi 38

我刚刚编写了这个Extension方法,因此您可以获取字符串中任何子字符串的第n个索引

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

注意:在此实现中,我使用1 = first,而不是基于0的索引.这可以很容易地改为使用0 =首先,通过添加nth++;到开头,并更改错误消息以便清楚.

  • 谢谢,谢谢您的帮助 (2认同)