markez
markez

Reputation: 3

How to split of string and for each determined character found add a new line

For example:

I have this:

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

I want to do that for each 4 found comma add a new line

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

Upvotes: 0

Views: 74

Answers (3)

Salah Akbari
Salah Akbari

Reputation: 39976

What about this:

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));

Just don't forget to add LINQ to your using directives first:

using System.Linq;

Upvotes: 3

Anas Sharabati
Anas Sharabati

Reputation: 67

Here you go :

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;
    }
}
}

Upvotes: 0

zaitsman
zaitsman

Reputation: 9519

Try this:

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);

Upvotes: 0

Related Questions