BLOG.CSHARPHELPER.COM: Use a second method to convert strings between Pascal case, camel case, and proper case in C#
Use a second method to convert strings between Pascal case, camel case, and proper case in C#
Thanks to Gary Winey for this version.
The example Convert strings between Pascal case, camel case, and proper case in C# explains one method for converting between Pascal case, camel case, and proper case. This example shows another approach.
The ToPascalCase extension method uses the following code to capitalize 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 together using Join.
The ToCamelCase method uses the following code to capitalize 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 code shows how the 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.
Comments