C# 在长字符串上每隔一个逗号拆分字符串

标签 c# .net string split

我有一个看起来像这样的字符串:

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/

相关文章:

Java:创建随机字符串数字数组

c# - 如何将图像添加到 DataGridView 中的单个特定单元格?

.net - 在VS中查找文本,包括.sln和.csproj文件

c# - LINQ to XML 使用 idref 连接

c# - 线程安全问题

c# - DataTable 使用列号而不是列名排序

python - 为什么 S == S[::-1] 比循环更快?

c - 将字符串存储在不规则数组中

c# - 使用 C#,如何在 Windows Vista,7,2008 中复制符号链接(symbolic link)

c# - 应用程序验证许可证执行情况?