Pascal case to human readable with C# extension methods

August 2nd 2008 11:02 pm

I needed to convert some Pascal case strings to human readable strings. Basically I have an enum containing errors, but wanted a nice way to convert them straight to messages for the exceptions that would be thrown.

Here’s how I did it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public static string ToHumanFromPascal(this string s)
{
    if (2 > s.Length)
    {
        return s;
    }
 
    var sb = new StringBuilder();
    var ca = s.ToCharArray();
    sb.Append(ca[0]);
    for (int i = 1; i < ca.Length - 1; i++)
    {
        char c = ca[i];
        if (char.IsUpper(c) && (char.IsLower(ca[i + 1]) || char.IsLower(ca[i - 1])))
        {
            sb.Append(' ');
        }
        sb.Append(c);
    }
    sb.Append(ca[ca.Length - 1]);
    return sb.ToString();
}

EDIT: Fixed to handle string of length 0 or 1.

Share and Enjoy:
  • Digg
  • Google
  • del.icio.us
  • Reddit
  • StumbleUpon
  • Technorati
  • Facebook
  • Live
  • LinkedIn
  • Sphinn
  • Mixx
  • Pownce
Start Slide Show with PicLens Lite PicLens

Posted by darkhelmet under Computers & Programming |

3 Responses to “Pascal case to human readable with C# extension methods”

  1. Dynamic Data and Custom Metadata Providers @ ZDima.net UNITED STATES responded on 01 Sep 2008 at 6:18 am #

    [...] Line 12: I first check to see if the property already has the DisplayNameAttribute defined. If it does I don’t do anything. But if it doesn’t have this attribute defined, I use the properties name to generate the friendly display name using the ToHumanFromPascal function (which I stole from here). [...]

  2. Steph CANADA responded on 19 Sep 2008 at 9:18 am #

    Oups!
    Your ToHumanFromPascal method will not handle properly strings that are 1 character long.

    Add the following at the end:

    if (ca.Length > 1)
    {
    sb.Append(ca[ca.Length – 1]);
    }

    :)
    That’s it!
    Stephane.

  3. darkhelmet CANADA responded on 19 Sep 2008 at 12:06 pm #

    Well to handle that I could do

    if (1 == s.length())
    return s;

    right at the beginning of the function. If the string is only 1 character long, all that is needed it to return the string, so this would solve the problem, unless I’m missing something.

Trackback URI | Comments RSS

Leave a Reply

My wishlist

 Subscribe in a reader
  • Categories

  • Monthly

  • Pages

  • Blogroll

  • Last.fm

  • Einstein@home

  • Word of the Day