wlz wlz - 1 year ago 204
C# Question

How can I convert text to Pascal case?

I have a variable name, say "WARD_VS_VITAL_SIGNS", and I want to convert it to Pascal case format: "WardVsVitalSigns"


How can I make this conversion?

Answer Source

First off, you are asking for title case and not camel-case, because in camel-case the first letter of the word is lowercase and your example shows you want the first letter to be uppercase.

At any rate, here is how you could achieve your desired result:

string textToChange = "WARD_VS_VITAL_SIGNS";
System.Text.StringBuilder resultBuilder = new System.Text.StringBuilder();

foreach(char c in textToChange)
    // Replace anything, but letters and digits, with space
        resultBuilder.Append(" ");

string result = resultBuilder.ToString();

// Make result string all lowercase, because ToTitleCase does not change all uppercase correctly
result = result.ToLower();

// Creates a TextInfo based on the "en-US" culture.
TextInfo myTI = new CultureInfo("en-US",false).TextInfo;

result = myTI.ToTitleCase(result).Replace(" ", String.Empty);

Note: result is now WardVsVitalSigns.

If you did, in fact, want camel-case, then after all of the above, just use this helper function:

public string LowercaseFirst(string s)
    if (string.IsNullOrEmpty(s))
        return string.Empty;

    char[] a = s.ToCharArray();
    a[0] = char.ToLower(a[0]);

    return new string(a);

So you could call it, like this:

result = LowercaseFirst(result);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download