String-Manipulation:拆分由字符分隔的字符串?

时间:2012-10-18 13:16:18

标签: c# string

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

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

我的目标是让这两个玩家分成两个新的字符串(对于第一个两个玩家来说):

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

我尝试了什么

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

也许有人可以帮助我。

2 个答案:

答案 0 :(得分:8)

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

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

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

答案 1 :(得分:0)

可以使用

"string".Split,但是你必须提供一个字符串数组,最简单的方法如下:

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

string firstPlayer = names[0];
string secondPlayer = names[1];
祝你好运:)