2012-10-18 169 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]; 

祝你好运:)

相关问题