【问题标题】:How to get the Index of second comma in a string如何获取字符串中第二个逗号的索引
【发布时间】:2014-05-05 07:55:32
【问题描述】:

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

我的字符串看起来像这样:

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;

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

非常感谢您的帮助!

【问题讨论】:

  • 字符串总是有2个逗号吗?
  • 你现在想开始学习正则表达式。
  • 你为什么不split(',') 然后将所有切片放在一个数组中?
  • @shree.pat18 好问题。有时有,有时没有 2 个逗号。

标签: c# .net string indexof


【解决方案1】:

你必须使用这样的代码。

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

你可能需要确保你没有超出字符串的范围。我会把这部分留给你。

【讨论】:

    【解决方案2】:

    我刚刚写了这个Extension方法,所以你可以得到一个字符串中任意子字符串的第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;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-12-15
      • 2022-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-19
      • 2023-03-29
      • 2017-10-04
      • 2014-06-08
      相关资源
      最近更新 更多