1

我有以下字符串(我在这里处理的是网球运动员的名字):

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";

我试过的

我解决了,用以下方法拆分第一个字符串/两个播放器(也解释了为什么我把“作品”作为评论放在后面)。第二个也有效,但它只是运气,因为我正在搜索第一个'-'然后拆分..但我无法让它适用于所有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;
}

也许有人可以帮助我。

4

2 回答 2

8

您的大部分代码都可以使用内置string.Split方法替换:

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

string firstPlayer = split[0];
string secondPlayer = split[1];
于 2012-10-18T13:19:23.983 回答
0

"string".Split可以使用,但您必须提供一个字符串数组,最简单的方法如下:

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

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

祝你好运 :)

于 2012-10-18T13:25:41.330 回答