Skip to content

Instantly share code, notes, and snippets.

@CallumWatkins
Last active June 27, 2017 19:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CallumWatkins/c02cb1bf4489f1fe442f5bbb92e8d0bb to your computer and use it in GitHub Desktop.
Save CallumWatkins/c02cb1bf4489f1fe442f5bbb92e8d0bb to your computer and use it in GitHub Desktop.
Splits a string into blocks of a specified length, delimited by a specified string. License: MIT
/// <summary>
/// Splits a string into blocks of a specified length, delimited by a specified string.
/// </summary>
/// <param name="value">The string to split up.</param>
/// <param name="partLength">The number of characters between each delimiter.</param>
/// <param name="delimiter">The delimiter to be inserted.</param>
public static string SplitInParts(string value, int partLength, string delimiter)
{
if (value == null) { throw new ArgumentNullException(nameof(value)); }
if (partLength < 1) { throw new ArgumentException("Part length must be positive and greater than zero.", nameof(partLength)); }
if (delimiter == null) { throw new ArgumentNullException(nameof(delimiter)); }
if (delimiter.Length == 0 || value.Length <= partLength)
{
return value;
}
var builder = new StringBuilder(value[0].ToString(), value.Length + (delimiter.Length * ((value.Length - 1) / partLength)));
for (int i = 1; i < value.Length; i++)
{
if (i % partLength == 0)
{
builder.Append(delimiter);
}
builder.Append(value[i]);
}
return builder.ToString();
}
// Usage:
SplitInParts("ABCDEFGHIJKLMNOPQRST", 5, "-");
// Returns: "ABCDE-FGHIJ-KLMNO-PQRST"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment