m-u
6/18/2014 - 8:38 AM

This method will return a string with spaces inserted before the capitals (excluding the first character).

This method will return a string with spaces inserted before the capitals (excluding the first character).

/// <summary>
/// This method will return a string with spaces inserted before the capitals (excluding the first character).
/// So, "ThisIsAString" will become "This Is A String" (hopefully)
/// </summary>
/// <param name="s">The string that you want to be nicely formatted</param>
/// <returns></returns>
public static string InsertSpaceBeforeCapitals(string s)
{
    char[] tmpTitleArr = s.ToCharArray();

    bool nextCharCapitalise = false;
    for (int i = 0; i < tmpTitleArr.Length; ++i)
    {
        //if not the first character and there isn't space before hand, insert one.
        if (i > 0 &&
            tmpTitleArr[i - 1] != ' ' &&
            Char.IsUpper(tmpTitleArr[i]))
        {
            char[] newTitleArr = new char[tmpTitleArr.Length + 1];

            bool inserted = false;
            for (int j = 0; j < tmpTitleArr.Length; ++j)
            {
                if (j == i)
                {
                    newTitleArr[j] = ' ';
                    inserted = true;
                }
                newTitleArr[j + (inserted ? 1 : 0)] = tmpTitleArr[j];
            }

            tmpTitleArr = newTitleArr;
        }

        //If this character is a space then we know the next character should be upper case.
        if (tmpTitleArr[i] == ' ' || i == 0)
        {
            nextCharCapitalise = true;
        }

        //Capitalise!
        if (nextCharCapitalise && Char.IsLetter(tmpTitleArr[i]))
        {
            tmpTitleArr[i] = Char.ToUpper(tmpTitleArr[i]);
            nextCharCapitalise = false;
        }
    }
    return new string(tmpTitleArr);
}