C# - Split String without removing the delimiter

By , 8/16/2013
(0 ratings)
This methods can split a String by a specified character without removing the delimiter.
It is possible to choose whether the delimiter should be kept before or behind the String parts. Moreover, empty String parts can be removed.

This methods are written as extensions for String.

Author: Koopakiller, translation by Michael List
/// <summary>
/// Splits a String by a specified Character.
/// </summary>
/// <param name="s">String to be splitted</param>
/// <param name="c">Delimiter</param>
/// <param name="after"><c>true</c> when the delimiter should be inserted before the Strings, otherwise <c>false</c>.</param>
/// <returns>String parts</returns>
public static string[] Split(this string s, char c, bool after)
{
    return Split(s, c, after, StringSplitOptions.None);
}
/// <summary>
/// Splits a String by a specified Character.
/// </summary>
/// <param name="s">String to be splitted</param>
/// <param name="c">Delimiter</param>
/// <param name="after"><c>true</c> when the delimiter should be inserted before the Strings, otherwise <c>false</c>.</param>
/// <param name="o">Additional options for splitting</param>
/// <returns>String parts</returns>
public static string[] Split(this string s, char c, bool after, StringSplitOptions o)
{
    string t = "";
    //Special chars in regex
    if (c == '.' || c == ',' || c == '+' || c == '-' || c == '*' || c == '(' || c == ')'
     || c == '[' || c == ']' || c == '{' || c == '}' || c == '|' || c == '?' || c == '\\')
        t = string.Concat(@"\", c);
    else if(c == ' ')
        t = @"\s"; // Whitespace
    else
        t = c.ToString(); // Other character
    if (o == StringSplitOptions.None)
        if (after)
            return Regex.Split(s, string.Concat(@"(?=", t, @")"));
        else
            return Regex.Split(s, string.Concat(@"(?<=", t, @")"));
    else
    {
        List<string> l = new List<string>();
        if (after)
            l.AddRange(Regex.Split(s, string.Concat(@"(?=", t, @")")));
        else
            l.AddRange(Regex.Split(s, string.Concat(@"(?<=", t, @")")));
        l.Remove("");//  Remove empty items
        return l.ToArray();
    }
}

Comments

 

Log in, to comment!