如何分割字符串,并为找到的每个确定的字符添加新行

时间:2018-09-02 07:31:40

标签: c# .net string

例如:

我有这个:

string commaSeparatedString = "124,45415,1212,4578,233,968,6865,32545,4545";

我要为每找到4个逗号添加一个新行

124-45415-1212-4578
233-968-6865-32545
4545

3 个答案:

答案 0 :(得分:3)

那呢:

string str = "124,45415,1212,4578,233,968,6865,32545,4545";
var result = string.Join("-", sss.Split(',').Select((c, index) => (index + 1) % 4 == 0 ?
                              c + Environment.NewLine : c));

别忘了先将LINQ添加到您的using指令中:

using System.Linq;

答案 1 :(得分:0)

尝试一下:

const int batch = 4;
var target = "124,45415,1212,4578,233,968,6865,32545,4545";
var items = target.Split(',');
var results = new List<string>();

var continue = false;
var step = 0;
do
{
    var slide = items.Skip(step++ * batch).Take(batch);
    continue = slide.Count() == batch;
    results.Add(string.Join('-', slide));
}while(continue);

答案 2 :(得分:0)

您在这里:

using System;

namespace ConsoleApp
{
class Program
{
    static void Main(string[] args)
    {
        Console.Write(SplitOnChar("124,45415,1212,4578,233,968,6865,32545,4545",',',4));
        Console.ReadKey();
    }

    private static string SplitOnChar(string input, char theChar, int number)
    {
        string result = "";
        int seen = 0;
        int lastSplitIndex = 0;

        for(int i = 0; i< input.Length;i++)
        {
            char c = input[i];
            if (c.Equals(theChar))
            {
                seen++;
                if (seen == number)
                {
                    result += input.Substring(lastSplitIndex + 1, i - lastSplitIndex -1);
                    result += Environment.NewLine;
                    lastSplitIndex = i;
                    seen = 0;
                }
            }
        }

        result += input.Substring(lastSplitIndex + 1);
        result = result.Replace(theChar, '-');
        return result;
    }
}
}