Skip to content

Instantly share code, notes, and snippets.

@caseywatson
Created August 26, 2016 14:36
Show Gist options
  • Save caseywatson/7639ad76fd1d0cae82bf83f6c602cc21 to your computer and use it in GitHub Desktop.
Save caseywatson/7639ad76fd1d0cae82bf83f6c602cc21 to your computer and use it in GitHub Desktop.
Similar to C# string.Split but splits on a condition, not a character array. Great for quick and easy string tokenization.
using System;
using System.Collections.Generic;
using System.Text;
namespace Extensions
{
public static class FunctionalStringSplitExtension
{
public static string[] Split(this string source, Func<char, bool> splitOn)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
source = source.Trim();
var stringParts = new List<string>();
var stringBuilder = new StringBuilder();
for (int i = 0; i < source.Length; i++)
{
var currentChar = source[i];
if (splitOn(currentChar))
{
if (stringBuilder.Length > 0)
{
stringParts.Add(stringBuilder.ToString());
stringBuilder.Clear();
}
}
else
{
stringBuilder.Append(currentChar);
}
}
if (stringBuilder.Length > 0)
stringParts.Add(stringBuilder.ToString());
return stringParts.ToArray();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment