2014-03-26 34 views
17

我有一个数组中的字符串,其中包含两个逗号以及制表符和空格。我试图在这个字符串中切出两个单词,两个都在逗号前面,我真的不关心这些标签和空格。如何获得字符串中的第二个逗号的索引

我的字符串看起来类似于此:

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; 

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

我真的很感谢你的帮忙!

+0

字符串是否总是有2个逗号? –

+3

你想现在开始学习正则表达式。 – leppie

+5

你为什么不分裂(',')'然后把所有切片放在一个数组中? – balexandre

回答

48

你必须使用这样的代码。

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

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

+1

谢谢你很多,它完美的作品 – Sem0

19

我刚才写的扩展方法,这样你就可以在一个字符串的任何字符串的第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; 
    } 
} 

注:在此实现我用1 =第一,而不是基于0的索引。

+1

谢谢,我感谢你的帮助 – Sem0

相关问题