Created
March 6, 2019 14:04
-
-
Save FSharpCSharp/469218f2ec13ef070fb3b8df7f6185d6 to your computer and use it in GitHub Desktop.
C# String.Split with Escape Character
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
| public static IEnumerable<string> Split(string text, char separator, char escapeCharacter, bool removeEmptyEntries) | |
| { | |
| var buffer = string.Empty; | |
| var escape = false; | |
| var split = new System.Collections.Generic.List<string>(); | |
| foreach (var c in text) | |
| if (!escape && c == separator) | |
| { | |
| if (!removeEmptyEntries || buffer.Length > 0) split.Add(buffer); | |
| buffer = string.Empty; | |
| } | |
| else | |
| { | |
| if (c == escapeCharacter) | |
| { | |
| escape = !escape; | |
| if (!escape) buffer = string.Concat(buffer, c); | |
| } | |
| else | |
| { | |
| if (!escape) buffer = string.Concat(buffer, c); | |
| escape = false; | |
| } | |
| } | |
| if (buffer.Length != 0) split.Add(buffer); | |
| return split; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment