Insert spaces between words on a camel-cased token

C#

C# Problem Overview


Is there a nice function to to turn something like

FirstName

to this:

First Name?

C# Solutions


Solution 1 - C#

See: https://stackoverflow.com/questions/155303/net-how-can-you-split-a-caps-delimited-string-into-an-array

Especially:

Regex.Replace("ThisIsMyCapsDelimitedString", "(\\B[A-Z])", " $1")

Solution 2 - C#

Here's an extension method that I have used extensively for this kind of thing

public static string SplitCamelCase( this string str )
{
    return Regex.Replace( 
        Regex.Replace( 
            str, 
            @"(\P{Ll})(\P{Ll}\p{Ll})", 
            "$1 $2" 
        ), 
        @"(\p{Ll})(\P{Ll})", 
        "$1 $2" 
    );
}

It also handles strings like IBMMakeStuffAndSellIt, converting it to IBM Make Stuff And Sell It (IIRC).

Syntax explanation (credit):

{Ll} is Unicode Character Category "Letter lowercase" (as opposed to {Lu} "Letter uppercase"). P is a negative match, while p is a positive match, so \P{Ll} is literally "Not lowercase" and p{Ll} is "Lowercase".
So this regex splits on two patterns. 1: "Uppercase, Uppercase, Lowercase" (which would match the MMa in IBMMake and result in IBM Make), and 2. "Lowercase, Uppercase" (which would match on the eS in MakeStuff). That covers all camelcase breakpoints.
TIP: Replace space with hyphen and call ToLower to produce HTML5 data attribute names.

Solution 3 - C#

Simplest Way:

var res = Regex.Replace("FirstName", "([A-Z])", " $1").Trim();

Solution 4 - C#

You can use a regular expression:

Match    ([^^])([A-Z])
Replace  $1 $2

In code:

String output = System.Text.RegularExpressions.Regex.Replace(
                  input,
                  "([^^])([A-Z])",
                  "$1 $2"
                );

Solution 5 - C#

    /// <summary>
    /// Parse the input string by placing a space between character case changes in the string
    /// </summary>
    /// <param name="strInput">The string to parse</param>
    /// <returns>The altered string</returns>
    public static string ParseByCase(string strInput)
    {
        // The altered string (with spaces between the case changes)
        string strOutput = "";

        // The index of the current character in the input string
        int intCurrentCharPos = 0;

        // The index of the last character in the input string
        int intLastCharPos = strInput.Length - 1;

        // for every character in the input string
        for (intCurrentCharPos = 0; intCurrentCharPos <= intLastCharPos; intCurrentCharPos++)
        {
            // Get the current character from the input string
            char chrCurrentInputChar = strInput[intCurrentCharPos];

            // At first, set previous character to the current character in the input string
            char chrPreviousInputChar = chrCurrentInputChar;
            
            // If this is not the first character in the input string
            if (intCurrentCharPos > 0)
            {
                // Get the previous character from the input string
                chrPreviousInputChar = strInput[intCurrentCharPos - 1];

            } // end if

            // Put a space before each upper case character if the previous character is lower case
            if (char.IsUpper(chrCurrentInputChar) == true && char.IsLower(chrPreviousInputChar) == true)
            {   
                // Add a space to the output string
                strOutput += " ";

            } // end if

            // Add the character from the input string to the output string
            strOutput += chrCurrentInputChar;

        } // next
        
        // Return the altered string
        return strOutput;

    } // end method

Solution 6 - C#

Regex:

http://weblogs.asp.net/jgalloway/archive/2005/09/27/426087.aspx http://stackoverflow.com/questions/773303/splitting-camelcase

(probably the best - see the second answer) http://bytes.com/topic/c-sharp/answers/277768-regex-convert-camelcase-into-title-case

> To convert from UpperCamelCase to > Title Case, use this line : > Regex.Replace("UpperCamelCase",@"(\B[A-Z])",@" > $1"); > > To convert from both lowerCamelCase > and UpperCamelCase to Title Case, use > MatchEvaluator : public string > toTitleCase(Match m) { char > c=m.Captures[0].Value[0]; return > ((c>='a')&&(c<='z'))?Char.ToUpper(c).ToString():" > "+c; } and change a little your regex > with this line : > Regex.Replace("UpperCamelCase or > lowerCamelCase",@"(\b[a-z]|\B[A-Z])",new > MatchEvaluator(toTitleCase));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOld ManView Question on Stackoverflow
Solution 1 - C#magmaView Answer on Stackoverflow
Solution 2 - C#ZombieSheepView Answer on Stackoverflow
Solution 3 - C#Karthik D VView Answer on Stackoverflow
Solution 4 - C#Tim CooperView Answer on Stackoverflow
Solution 5 - C#Kevin PattonView Answer on Stackoverflow
Solution 6 - C#Ryan BennettView Answer on Stackoverflow