2012-10-18 167 views
1

我有以下字符串(我在這裏處理Tennisplayers的名稱):字符串操作:將此字符串拆分爲 - 字符?

string bothPlayers = "N. Djokovic - R. Nadal"; //works with my code 
string bothPlayer2 = "R. Federer - G. Garcia-Lopez"; //works with my code 
string bothPlayer3 = "G. Garcia-Lopez - R. Federer"; //doesnt works 
string bothPlayer4 = "E. Roger-Vasselin - G. Garcia-Lopez"; //doesnt works 

我的目標是讓這些球員都在兩個新的字符串(這將是第一bothPlayers)分隔:

string firstPlayer = "N. Djokovic"; 
string secondPlayer = "R. Nadal"; 

我試過

我解決,拆分第一個字符串/以下方法bothPlayers(也解釋了爲什麼我把「作品」的評論背後)。該塞康d還工作,但它只是運氣我searchin爲先「 - 」和分裂的話.. 但我不能讓所有4種情況下工作。這裏是我的方法:

string bothPlayers = "N. Djokovic - R. Nadal"; //works 
string bothPlayer2 = "R. Federer - G. Garcia-Lopez"; //works 
string bothPlayer3 = "G. Garcia-Lopez - R. Federer"; //doesnt works 
string bothPlayer4 = "E. Roger-Vasselin - G. Garcia-Lopez"; //doesnt works 

string firstPlayerName = String.Empty; 
string secondPlayerName = String.Empty; 

int index = -1; 
int countHyphen = bothPlayers.Count(f=> f == '-'); //Get Count of '-' in String 

index = GetNthIndex(bothPlayers, '-', 1); 
if (index > 0) 
{ 
    firstPlayerName = bothPlayers.Substring(0, index).Trim(); 
    firstPlayerName = firstPlayerName.Trim(); 

    secondPlayerName = bothPlayers.Substring(index + 1, bothPlayers.Length - (index + 1)); 
    secondPlayerName = secondPlayerName.Trim(); 

    if (countHyphen == 2) 
    { 
     //Maybe here something?.. 
    } 
} 

//Getting the Index of a specified character (Here for us: '-') 
public int GetNthIndex(string s, char t, int n) 
{ 
    int count = 0; 
    for (int i = 0; i < s.Length; i++) 
    { 
     if (s[i] == t) 
     { 
      count++; 
      if (count == n) 
      { 
       return i; 
      } 
     } 
    } 
    return -1; 
} 

也許有人可以幫助我。

+3

你不能用'string.Split(新的String [] { 「 - 」})任何理由'? – Oded

+0

沒有理由..可以使用任何東西..我只是不是很好,在解決這樣的字符串操作問題:)) – eMi

+0

@Oded,不'string.Split'有一個字符數組,而不是它分裂的字符串? –

回答

8

大部分代碼可以通過使用內置的string.Split方法來代替:

var split = "N. Djokovic - R. Nadal".Split(new string[] {" - "}, 
              StringSplitOptions.None); 

string firstPlayer = split[0]; 
string secondPlayer = split[1]; 
+0

也適用於我的情況也..但不適合所有的遊戲:) ..你如何處理:「E.羅傑Vasselin - G.加西亞 - 洛佩茲」?有3' - ' – eMi

+2

它確實工作,因爲''''和'' - ''在分裂 – KyorCode

+0

哦之間有區別哦,我其實沒有考慮(空格)..好的,謝謝:) – eMi

0

"string".Split可以使用,但你必須提供一個字符串數組,最簡單的方法是以下:

string[] names = bothPlayers.Split(new string[]{" "}, StringSplitOptions.None); 

string firstPlayer = names[0]; 
string secondPlayer = names[1]; 

祝你好運:)

相關問題