我有一个像这样的字符串:
mystring = "test1, 1, anotherstring, 5, yetanother, 400";
Run Code Online (Sandbox Code Playgroud)
myarray可以有不同的长度.我想做的是像这样拆分字符串:
{"test1, 1"}
{"anotherstring, 5}
{"yetanother, 400"}
Run Code Online (Sandbox Code Playgroud)
这可能吗?我尝试了,string[] newArray = mystring.Split(',')
但是在每个逗号分开它,而不是我想做的第二个逗号.
谢谢你的帮助
跳越
您可以使用正则表达式匹配字符串中的两个项目:
string[] parts =
Regex.Matches(myarray[0], "([^,]*,[^,]*)(?:, |$)")
.Cast<Match>()
.Select(m => m.Groups[1].Value)
.ToArray();
Run Code Online (Sandbox Code Playgroud)
这将从数组中的第一个字符串中获取项目.我不知道你为什么在数组中有字符串,如果你有多个字符串,在这种情况下你必须遍历它们并从每个字符串中获取项目.
没有直接方法可以使String.Split做到这一点。
如果不关心性能,则可以使用LINQ:
var input = "test1, 1, anotherstring, 5, yetanother, 400";
string[] result = input.Split(',');
result = result.Where((s, i) => i % 2 == 0)
.Zip(result.Where((s, i) => i % 2 == 1), (a, b) => a + ", " + b)
.ToArray();
Run Code Online (Sandbox Code Playgroud)
否则,您可能必须使用String.IndexOf或使用正则表达式手动拆分字符串。
归档时间: |
|
查看次数: |
4794 次 |
最近记录: |