如何拆分字符串并找到每个确定的字符添加一个新行

问题描述 投票:0回答:3

例如:

我有这个:

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

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

124-45415-1212-4578
233-968-6865-32545
4545
c# .net string
3个回答
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);

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;

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;
    }
}
}
© www.soinside.com 2019 - 2024. All rights reserved.