public static string[] SplitWithSeparators(this string text, string[] separators, IncludedSeparatorsLocation includedSeparatorsLocation) { return text.SplitWithSeparators(separators, includedSeparatorsLocation, StringSplitOptions.RemoveEmptyEntries); }
/// <summary> /// Splits the string by a specified collection of separator strings and includes both the split strings and the separators in the returned list. /// </summary> public static string[] SplitWithSeparators(this string text, string[] separators, IncludedSeparatorsLocation includedSeparatorsLocation, StringSplitOptions splitOptions) { if (text == null) return null; var parts = new List<string>(); var i = 0; var j = 0; string token; while (j < text.Length) { //Look for a separator string at the current index string foundSeparator = null; var substring = text.Substring(j); foreach (var separator in separators) { if (substring.StartsWith(separator)) { foundSeparator = separator; break; } } //If the current index begins with a separator string... if (foundSeparator != null) { token = text.Substring(i, j - i); switch (includedSeparatorsLocation) { case IncludedSeparatorsLocation.SeparateToken: if (token.IsNotEmpty() || splitOptions == StringSplitOptions.None) parts.Add(token); parts.Add(foundSeparator); break; case IncludedSeparatorsLocation.AppendedToTokens: parts.Add(token + foundSeparator); break; } //Start on the next token j += foundSeparator.Length; i = j; } //Otherwise, continue building the current token else { j++; } } //Add the last token to the list token = text.Substring(i, j - i); parts.Add(token); return parts.ToArray(); }
public static string[] SplitWithSeparators(this string text, char[] separators, IncludedSeparatorsLocation includedSeparatorsLocation, StringSplitOptions splitOptions) { return text.SplitWithSeparators(ToStringArray(separators), includedSeparatorsLocation, splitOptions); }