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

本文关键字:第二个 索引 字符串 | 更新日期: 2023-09-27 17:54:11

在数组中有一个字符串,它包含两个逗号以及制表符和空格。我试着在字符串中剪掉两个单词,它们都在逗号之前,我真的不关心制表符和空格。

My String看起来像这样:

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;

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

我真的很感谢你的帮助!

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

你必须使用这样的代码。

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

您可能需要确保您没有超出字符串的边界。我把那部分留给你。

我刚刚编写了这个扩展方法,因此您可以获得字符串中任何子字符串的第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;
    }
}

LastIndexOf给出给定字符/字符串最后出现的索引。

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