Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert spaces between words on a camel-cased token [duplicate]

Tags:

c#

People also ask

What is CamelCase string?

Camelcase is the practice of writing phrases without any spaces or punctuation between words. To indicate the separation between words, we isntead use a single capitalized letter for each word. Below are some examples: someLabelThatNeedsToBeCamelized. someMixedString.

What is camel case character?

The camel case character is defined as the number of uppercase characters in the given string. Explanation: Camel case characters present are U, U, Y, I and I.

What is camel case sentence?

Camel case (sometimes stylized as camelCase or CamelCase, also known as camel caps or more formally as medial capitals) is the practice of writing phrases without spaces or punctuation. It indicates the separation of words with a single capitalized letter, and the first word starting with either case.


See: .NET - How can you split a "caps" delimited string into an array?

Especially:

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

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.


Simplest Way:

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

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"
                );

    /// <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

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));