我有以下字符串(我在这里处理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;
}
也许有人可以帮助我。
你不能用'string.Split(新的String [] { “ - ”})任何理由'? – Oded
没有理由..可以使用任何东西..我只是不是很好,在解决这样的字符串操作问题:)) – eMi
@Oded,不'string.Split'有一个字符数组,而不是它分裂的字符串? –