gpt4 book ai didi

c# - 字符串操作:以-字符分隔此字符串吗?

转载 作者:太空宇宙 更新时间:2023-11-03 18:12:02 26 4
gpt4 key购买 nike

我有以下字符串(我在这里处理的是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(也解释了为什么在后面加上“ works”作为注释)。第二个也可行,但是运气不错,因为我正在搜索第一个“-”然后分开
但是我无法使它适用于所有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;
}


也许有人可以帮助我。

最佳答案

您可以使用内置的方法来替换大多数代码:

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com