Convert between Pascal case, camel case, and proper case method 2 in C#

example

Like the previous post, Convert between Pascal case, camel case, and proper case in C#, this example shows how to use string extension methods convert strings into various case types. Thanks to Gary Winey for this version.

The following ToPascalCase extension method capitalizes the first letter in each of a string’s words.

// Convert the string to Pascal case.
public static string ToPascalCase(this string the_string)
{
    TextInfo info = Thread.CurrentThread.CurrentCulture.TextInfo;
    the_string = info.ToTitleCase(the_string);
    string[] parts = the_string.Split(new char[] {},
        StringSplitOptions.RemoveEmptyEntries);
    string result = String.Join(String.Empty, parts);
    return result;
}

This code uses a TextInfo object’s ToTitleCase method to convert the string into title case, which capitalizes the first letter in each of its words. It then splits the string into words and concatenates them using Join to produce the final Pascal case result.

The following ToCamelCase method capitalizes the first letter in each word except for the first word.

// Convert the string to camel case.
public static string ToCamelCase(this string the_string)
{
    the_string = the_string.ToPascalCase();
    return the_string.Substring(0, 1).ToLower() +
        the_string.Substring(1);
}

This code simply calls ToPascalCase and then converts the first letter to lower case.

The following ToProperCase method splits a Pascal case or camel case string into words and capitalizes each.

// Capitalize the first character and add a space before
// each capitalized letter (except the first character).
public static string ToProperCase(this string the_string)
{
    const string pattern = @"(?<=\w)(?=[A-Z])";
    //const string pattern = @"(?<=[^A-Z])(?=[A-Z])";
    string result = Regex.Replace(the_string, pattern,
        " ", RegexOptions.None);
    return result.Substring(0, 1).ToUpper() + result.Substring(1);
}

This code uses a regular expression to find places where a word is followed by a capital letter and replaces those locations with a space character to separate the words in the string. The code then capitalizes the first letter in the string and returns the result.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in extension methods, strings and tagged , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *