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

60

我有一个包含两个逗号以及制表符和空格的数组中的字符串。我想要在该字符串中截取两个单词,它们都在逗号之前,我不介意制表符和空格。

我的字符串类似于以下内容:

String s = "Address1       Chicago,  IL       Address2     Detroit, MI"

我获得第一个逗号的索引

int x = s.IndexOf(',');

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

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

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

非常感谢您的帮助!


这个字符串是否总是有两个逗号? - shree.pat18
4
你现在想开始学习正则表达式。 - leppie
11
为什么不使用 split(',') 将字符串分割成数组,然后将所有的切片放在一个数组中? - balexandre
@shree.pat18 很好的问题。有时候它会有两个逗号,有时候则没有。 - Sem0
2
获取字符串中第n个字符出现的索引 - huMpty duMpty
显示剩余2条评论
3个回答

115

你必须使用像这样的代码。

int index = s.IndexOf(',', s.IndexOf(',') + 1);

你可能需要确保不超出字符串的边界,但这部分我将留给你自己处理。


69

我刚刚写了这个扩展方法,可以获取字符串中任何子字符串的第n个索引。

注意:要获取第一次出现的索引,请使用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;
    }
}

-1

LastIndexOf可以给你一个字符/字符串最后一次出现的索引。

int index = s.LastIndexOf(',');

请在您的回答中添加更多细节,解释您的代码如何工作以及如何回答OP的问题,这不仅对提问者有帮助,也对未来的研究人员有帮助。 - Kuro Neko
这不是第二个,而是最后一个。 - Paramar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接