我有一个看起来像这样的字符串:
string a = "Stuff, another thing, random stuff, snuff, Pigs are wierd, sick, Cats are dangerous, they will kill you, Cows produce milk, but horses don't"
所以我的目标是检索一个看起来像这样的字符串
string output = "Stuff, another thing
Random stuff, snuff
Pigs are wierd, sick
Cats are dangerous, they will kill you
Cows produce milk, but horses don't"
尝试使用正则表达式来做到这一点,但如果字符串以一种好的方式更长,则无法真正让它正确分组。
string[] output = Regex.Split(a, "^([^,]+(?:,[^,]+){1})");
有什么建议吗?
最佳答案
将其沿所有逗号拆分,然后重新组合成以逗号分隔的对。
using System;
public class Program
{
public static void Main()
{
string a = "Stuff, another thing, random stuff, snuff, Pigs are wierd, sick, Cats are dangerous, they will kill you, Cows produce milk, but horses don't";
string[] splittedStrings = a.Split(new[]{", "}, StringSplitOptions.None);
for (var i = 0; i < splittedStrings.Length / 2; i++)
{
Console.WriteLine(splittedStrings[i*2] + ", " + splittedStrings[i*2 + 1]);
}
if(splittedStrings.Length % 2 == 1)
{
Console.WriteLine(splittedStrings[splittedStrings.Length-1]);
}
}
}
关于C# 在长字符串上每隔一个逗号拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53798212/