Friday, May 18, 2012

How to: String to Pascal case from C#

We can return a string to Pascal case using regular expression or using our own logic. Here are two scenarios for doing this.

Method 1: Regular expression

public static string ToPascalCase(string pascalCaseString)
{
Regex r = new Regex("(?<=[a-z])(?<x>[A-Z])|(?<=.)(?<x>[A-Z])(?=[a-z])");
return r.Replace(pascalCaseString, " ${x}");
}


Method 2: String parsing.


/// <summary>
/// Convert the string to Pascal case.
/// </summary>
/// <param name="str">the string to turn into Pascal case</param>
/// <returns>a string formatted as Pascal case</returns>
public static string FormatPascalCase(string str)
{
StringBuilder sb = new StringBuilder(str.Length);
if (string.IsNullOrEmpty(str))
throw new ArgumentException("A null or empty value cannot be converted", str);

if (str.Length < 2)
return str.ToUpper();
// Split the string into words.
string[] words = str.Split(new char[] { }, StringSplitOptions.RemoveEmptyEntries);
foreach (string word in words)
sb.Append(string.Format("{0}{1}", word.Substring(0, 1).ToUpper(), word.Substring(1)));
return sb.ToString();
}

Hope this helps.

No comments:

Post a Comment