65.9K
CodeProject is changing. Read more.
Home

Pascal and Camel Case to Display Text Conversion

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.86/5 (4 votes)

Jun 7, 2011

CPOL
viewsIcon

17104

Why not take care of the first character before the loop, instead of checking it every time (not that it makes a big difference on modern hardware)? This also moves the char declaration out of the loop.private string createDisplayText(string propertyName){ if...

Why not take care of the first character before the loop, instead of checking it every time (not that it makes a big difference on modern hardware)? This also moves the char declaration out of the loop.
private string createDisplayText(string propertyName)
{
    if (String.IsNullOrEmpty(propertyName))
    {
        return String.Empty;
    }

    StringBuilder builder = new StringBuilder();
    char character = char.ToUpper(propertyName[0]);
    builder.Append(character);

    for (int i = 1; i < propertyName.Length; ++i)
    {
        character = propertyName[i];
        if (char.IsUpper(character))
        {
            builder.Append(" ");
        }
        builder.Append(character);
    }

    return builder.ToString();
}
This isn't really an alternate, as much as a minor modification. Also, the for loop could be shorter, if somewhat less readable.
for (int i = 1; i < propertyName.Length; ++i)
{
    character = propertyName[i];
    builder.Append((char.IsUpper(character)) ? ' ' + character : character);
}