Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I programmatically change CamelCase names to displayable names

Tags:

string

c#

I would like to take a class name or enumeration name that is camel case and display it in normal text for the user. How can I programmatically do this?

An sample input:

MainPageBackgroundColor

Expected output:

Main page background color

or

Main Page Background Color

like image 592
Lance McCarthy Avatar asked Jun 13 '13 17:06

Lance McCarthy


2 Answers

A regex option:

public static string ToMeaningfulName(this string value)
{
    return Regex.Replace(value, "(?!^)([A-Z])", " $1");
}

Input "MainPageBackgroundColor"

Output- "Main Page Background Color"

like image 62
nawfal Avatar answered Oct 23 '22 11:10

nawfal


You can convert a string from CamelCase to a displayable string separated by spaces via:

public static string DisplayCamelCaseString(string camelCase)
{
    List<char> chars = new List<char>();
    chars.Add(camelCase[0]);
    foreach(char c in camelCase.Skip(1))
    {
        if (char.IsUpper(c))
        {
            chars.Add(' ');
            chars.Add(char.ToLower(c));
        }
        else
            chars.Add(c);
    }

    return new string(chars.ToArray());
}

This will convert from "CamelCase" to "Camel case" or "SomeRandomEnumeration" to "Some random enumeration".

like image 23
Reed Copsey Avatar answered Oct 23 '22 12:10

Reed Copsey