C# string.split() separate string by uppercase

Use Regex.split

string[] split =  Regex.Split(str, @"(?<!^)(?=[A-Z])");

If you do not like RegEx and you really just want to insert the missing spaces, this will do the job too:

public static string InsertSpaceBeforeUpperCase(this string str)
{   
    var sb = new StringBuilder();

    char previousChar = char.MinValue; // Unicode '\0'

    foreach (char c in str)
    {
        if (char.IsUpper(c))
        {
            // If not the first character and previous character is not a space, insert a space before uppercase

            if (sb.Length != 0 && previousChar != ' ')
            {
                sb.Append(' ');
            }           
        }

        sb.Append(c);

        previousChar = c;
    }

    return sb.ToString();
}

Another way with regex:

public static string SplitCamelCase(string input)
{
   return System.Text.RegularExpressions.Regex.Replace(input, "([A-Z])", " $1", System.Text.RegularExpressions.RegexOptions.Compiled).Trim();
}

Tags:

C#

String

Split