我有以下字符串(我在這裏處理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'有一個字符數組,而不是它分裂的字符串? –