2014-03-26 33 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

相關問題