gpt4 book ai didi

C# 字符串拆分 - 在第二个逗号处拆分字符串

转载 作者:太空狗 更新时间:2023-10-29 18:12:46 25 4
gpt4 key购买 nike

我有这样一个字符串:

mystring = "test1, 1, anotherstring, 5, yetanother, 400";

myarray 可以有不同的长度。我想做的是像这样拆分字符串:

{"test1, 1"} 
{"anotherstring, 5}
{"yetanother, 400"}

这可能吗?我尝试了 string[] newArray = mystring.Split(',') 但是它在每个逗号处拆分它,而不是我想要做的第二个逗号。

谢谢你的帮助

闪电

最佳答案

您可以使用正则表达式来匹配字符串中的两个项目:

string[] parts =
Regex.Matches(myarray[0], "([^,]*,[^,]*)(?:, |$)")
.Cast<Match>()
.Select(m => m.Groups[1].Value)
.ToArray();

这从数组中的第一个字符串中获取项目。我不知道为什么你在数组中有字符串,如果你有多个字符串,在这种情况下你必须遍历它们并从每个字符串中获取项目。

关于C# 字符串拆分 - 在第二个逗号处拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3254680/

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