I have following strings (I'm dealing here with the names of 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
My aim is to get these both players, separated in two new strings (for the first bothPlayers it would be):
string firstPlayer = "N. Djokovic";
string secondPlayer = "R. Nadal";
What I tried
I solved, to split the first string/bothPlayers with the following method (also explains why I put "works" as a comment behind).. The Second also works, but its just luck as I'm searchin for the first '-' and split then.. But I'm not able to make it work for all 4 cases.. Here's my Method:
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;
}
Maybe someone could help me.