Splitting a string / number every Nth Character / Number?

C#.NetStringSplit

C# Problem Overview


I need to split a number into even parts for example:

32427237 needs to become 324 272 37
103092501 needs to become 103 092 501

How does one go about splitting it and handling odd number situations such as a split resulting in these parts e.g. 123 456 789 0?

C# Solutions


Solution 1 - C#

If you have to do that in many places in your code you can create a fancy extension method:

static class StringExtensions {

  public static IEnumerable<String> SplitInParts(this String s, Int32 partLength) {
    if (s == null)
      throw new ArgumentNullException(nameof(s));
    if (partLength <= 0)
      throw new ArgumentException("Part length has to be positive.", nameof(partLength));

    for (var i = 0; i < s.Length; i += partLength)
      yield return s.Substring(i, Math.Min(partLength, s.Length - i));
  }

}

You can then use it like this:

var parts = "32427237".SplitInParts(3);
Console.WriteLine(String.Join(" ", parts));

The output is 324 272 37 as desired.

When you split the string into parts new strings are allocated even though these substrings already exist in the original string. Normally, you shouldn't be too concerned about these allocations but using modern C# you can avoid this by altering the extension method slightly to use "spans":

public static IEnumerable<ReadOnlyMemory<char>> SplitInParts(this String s, Int32 partLength)
{
    if (s == null)
        throw new ArgumentNullException(nameof(s));
    if (partLength <= 0)
        throw new ArgumentException("Part length has to be positive.", nameof(partLength));

    for (var i = 0; i < s.Length; i += partLength)
        yield return s.AsMemory().Slice(i, Math.Min(partLength, s.Length - i));
}

The return type is changed to public static IEnumerable<ReadOnlyMemory<char>> and the substrings are created by calling Slice on the source which doesn't allocate.

Notice that if you at some point have to convert ReadOnlyMemory<char> to string for use in an API a new string has to be allocated. Fortunately, there exists many .NET Core APIs that uses ReadOnlyMemory<char> in addition to string so the allocation can be avoided.

Solution 2 - C#

You could use a simple for loop to insert blanks at every n-th position:

string input = "12345678";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < input.Length; i++)
{
    if (i % 3 == 0)
        sb.Append(' ');
    sb.Append(input[i]);
}
string formatted = sb.ToString();

Solution 3 - C#

One very simple way to do this (not the most efficient, but then not orders of magnitude slower than the most efficient).

    public static List<string> GetChunks(string value, int chunkSize)
    {
        List<string> triplets = new List<string>();
        while (value.Length > chunkSize)
        {
            triplets.Add(value.Substring(0, chunkSize));
            value = value.Substring(chunkSize);
        }
        if (value != "")
            triplets.Add(value);
        return triplets;
    }

Heres an alternate

    public static List<string> GetChunkss(string value, int chunkSize)
    {
        List<string> triplets = new List<string>();
        for(int i = 0; i < value.Length; i += chunkSize)
            if(i + chunkSize > value.Length)
                triplets.Add(value.Substring(i));
            else
                triplets.Add(value.Substring(i, chunkSize));

        return triplets;
    }

Solution 4 - C#

LINQ rules:

var input = "1234567890";
var partSize = 3;

var output = input.ToCharArray()
    .BufferWithCount(partSize)
    .Select(c => new String(c.ToArray()));

UPDATED:

string input = "1234567890";
double partSize = 3;
int k = 0;
var output = input
    .ToLookup(c => Math.Floor(k++ / partSize))
    .Select(e => new String(e.ToArray()));

Solution 5 - C#

This is half a decade late but:

int n = 3;
string originalString = "32427237";
string splitString = string.Join(string.Empty,originalString.Select((x, i) => i > 0 && i % n == 0 ? string.Format(" {0}", x) : x.ToString()));

Solution 6 - C#

The splitting method:

public static IEnumerable<string> SplitInGroups(this string original, int size) {
  var p = 0;
  var l = original.Length;
  while (l - p > size) {
    yield return original.Substring(p, size);
    p += size;
  }
  yield return original.Substring(p);
}

To join back as a string, delimited by spaces:

var joined = String.Join(" ", myNumber.SplitInGroups(3).ToArray());

Edit: I like Martin Liversage solution better :)

Edit 2: Fixed a bug.

Edit 3: Added code to join the string back.

Solution 7 - C#

If you know that the whole string's length is exactly divisible by the part size, then use:

var whole = "32427237!";
var partSize = 3;
var parts = Enumerable.Range(0, whole.Length / partSize)
    .Select(i => whole.Substring(i * partSize, partSize));

But if there's a possibility the whole string may have a fractional chunk at the end, you need to little more sophistication:

var whole = "32427237";
var partSize = 3;
var parts = Enumerable.Range(0, (whole.Length + partSize - 1) / partSize)
    .Select(i => whole.Substring(i * partSize, Math.Min(whole.Length - i * partSize, partSize)));

In these examples, parts will be an IEnumerable, but you can add .ToArray() or .ToList() at the end in case you want a string[] or List<string> value.

Solution 8 - C#

I would do something like this, although I'm sure there are other ways. Should perform pretty well.

public static string Format(string number, int batchSize, string separator)
{      
  StringBuilder sb = new StringBuilder();
  for (int i = 0; i <= number.Length / batchSize; i++)
  {
    if (i > 0) sb.Append(separator);
    int currentIndex = i * batchSize;
    sb.Append(number.Substring(currentIndex, 
              Math.Min(batchSize, number.Length - currentIndex)));
  }
  return sb.ToString();
}

Solution 9 - C#

I like this cause its cool, albeit not super efficient:

var n = 3;
var split = "12345678900"
            .Select((c, i) => new { letter = c, group = i / n })
            .GroupBy(l => l.group, l => l.letter)
            .Select(g => string.Join("", g))
            .ToList();

Solution 10 - C#

Try this:

Regex.Split(num.toString(), "(?<=^(.{8})+)");

Solution 11 - C#

A nice implementation using answers from other StackOverflow questions:

"32427237"
    .AsChunks(3)
    .Select(vc => new String(vc))
    .ToCsv(" ");  // "324 272 37"

"103092501"
    .AsChunks(3)
    .Select(vc => new String(vc))
    .ToCsv(" "); // "103 092 501"

AsChunks(): https://stackoverflow.com/a/22452051/538763

ToCsv(): https://stackoverflow.com/a/45891332/538763

Solution 12 - C#

This might be off topic as I don't know why you wish to format the numbers this way, so please just ignore this post if it's not relevant...

How an integer is shown differs across different cultures. You should do this in a local independent manner so it's easier to localize your changes at a later point.

int.ToString takes different parameters you can use to format for different cultures. The "N" parameter gives you a standard format for culture specific grouping.

steve x string formatting is also a great resource.

Solution 13 - C#

For a dividing a string and returning a list of strings with a certain char number per place, here is my function:

public List<string> SplitStringEveryNth(string input, int chunkSize)
    {
        var output = new List<string>();
        var flag = chunkSize;
        var tempString = string.Empty;
        var lenght = input.Length;
        for (var i = 0; i < lenght; i++)
        {
            if (Int32.Equals(flag, 0))
            {
                output.Add(tempString);
                tempString = string.Empty;
                flag = chunkSize;
            }
            else
            {
                tempString += input[i];
                flag--;
            }

            if ((input.Length - 1) == i && flag != 0)
            {
                tempString += input[i];
                output.Add(tempString);
            }
        }
        return output;
    }

Solution 14 - C#

You can try something like this using Linq.

var str = "11223344";
var bucket = 2;    
var count = (int)Math.Ceiling((double)str.Length / bucket);
		
Enumerable.Range(0, count)
    .Select(_ => (_ * bucket))
	.Select(_ => str.Substring(_,  Math.Min(bucket, str.Length - _)))
	.ToList()

Solution 15 - C#

You can also use the StringReader class to reads a block of characters from the input string and advances the character position by count.

StringReader Class Read(Char[], Int32, Int32)

Solution 16 - C#

The simplest way to separate thousands with a space, which actually looks bad, but works perfect, would be:

yourString.ToString("#,#").Replace(',', ' ');

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRoguePlanetoidView Question on Stackoverflow
Solution 1 - C#Martin LiversageView Answer on Stackoverflow
Solution 2 - C#Dirk VollmarView Answer on Stackoverflow
Solution 3 - C#Binary WorrierView Answer on Stackoverflow
Solution 4 - C#QrystaLView Answer on Stackoverflow
Solution 5 - C#TyressView Answer on Stackoverflow
Solution 6 - C#Fábio BatistaView Answer on Stackoverflow
Solution 7 - C#Dave LampertView Answer on Stackoverflow
Solution 8 - C#steinarView Answer on Stackoverflow
Solution 9 - C#Sam SaffronView Answer on Stackoverflow
Solution 10 - C#esdebonView Answer on Stackoverflow
Solution 11 - C#crokusekView Answer on Stackoverflow
Solution 12 - C#simendsjoView Answer on Stackoverflow
Solution 13 - C#António SobrinhoView Answer on Stackoverflow
Solution 14 - C#Raj ParekhView Answer on Stackoverflow
Solution 15 - C#bjhamltnView Answer on Stackoverflow
Solution 16 - C#Josan SolomonView Answer on Stackoverflow