11

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

Community
  • 1
  • 1
Lance McCarthy
  • 1,884
  • 1
  • 20
  • 40
  • lowercase the whole string then uppercase the first letter. could be done easily in one line of code – Jonesopolis Jun 13 '13 at 17:33
  • Can you give some samples of what you want for output? – Reed Copsey Jun 13 '13 at 17:57
  • I should also add that I already know what the enumerations look like, so I'm not expecting bad encoding. Here is an example: BackgroundColor would be displayed to the user as Background color in a combobox's Header property and the enumeration's values are populating the combobox. The user selects a color and it updates the ViewModel/UI. – Lance McCarthy Jun 13 '13 at 19:20
  • @LanceMcCarthy I found [this](http://stackoverflow.com/a/155487/1180426) regex to be most useful in splitting pascal cased names into separate words - and I wanted it to handle uppercase acronyms too. – Patryk Ćwiek Jun 13 '13 at 19:31

6 Answers6

11

A regex option:

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

Input "MainPageBackgroundColor"

Output- "Main Page Background Color"

nawfal
  • 70,104
  • 56
  • 326
  • 368
8

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".

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
2

Just to round things out, an alternative solution using Linq with extension methods.

public static string ToSentenceCase(this string value)
{
    string[] spacedWords
        = ((IEnumerable<char>)value).Skip(1)
        .Select(c => c == char.ToUpper(c)
            ? " " + char.ToLower(c).ToString() 
            : c.ToString()).ToArray();

    string result = value.Substring(0, 1)
        + (String.Join("", spacedWords)).Trim();

    return result;
}

Returns: "Main page background color"

public static string ToTitleCase(this string value)
{
    string[] spacedWords 
        = ((IEnumerable<char>)value)
        .Select(c => c == char.ToUpper(c) 
            ? " " + c.ToString() 
            : c.ToString()).ToArray();

    return (String.Join("", spacedWords)).Trim();
}

Returns: "Main Page Background Color"

1
string a = "asdfaGasfdasdAA";
a = a.Substring(0,1).ToUpper() + a.Substring(1,a.Length-1).ToLower();

I took Jonesy's comment as a challenge...

Sayse
  • 42,633
  • 14
  • 77
  • 146
0

Here is the way I first did it. It's fast and works as expected, but after seeing the other answers, I changed it to the one I marked as Answer.

public static string CamelCaseToDisplayName<T>(this T enumeration)
{
    string name = enumeration.ToString();

    for (int i = 1; i < name.Length; i++)
    {
        char c = name[i];

        if (c >= 'A' && c <= 'Z')
        {
            name = name.Remove(i, 1);
            name = name.Insert(i++, ((char)(c + 0x30)).ToString());
            name = name.Insert(i, " ");
        }
    }

    return name;
}
Lance McCarthy
  • 1,884
  • 1
  • 20
  • 40
  • What happens when the character encoding is different? The answer is you get garbage output. If you want to make it more readable just insert spaces. The names are proper nouns after all, English dictates the first letter of each word is uppercase. – evanmcdonnal Jun 13 '13 at 17:38
  • This won't work - Remove/Insert/etc make new strings, they don't mutate the input... – Reed Copsey Jun 13 '13 at 17:45
  • (Should be `name = name.Remove(i, 1);`, etc) That being said, I'd suggest using the methods built into `System.Char`) – Reed Copsey Jun 13 '13 at 18:00
0

An example with the StringBuilder class and expressed as an Extension Method.

public static string ToCapitalWithSpaces(this string status)
        {
            var response = new StringBuilder(status[..1]);

            foreach (var chr in status.Skip(1))
            {
                if (char.IsUpper(chr))
                    response.Append(" ");

                response.Append(chr);
            }

            return response.ToString();
        }
Regianni
  • 229
  • 1
  • 3
  • 11