Created
August 26, 2016 14:36
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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