Home
Manage Your Code
Snippet: Convert String to CamelCase and PascalCase (C#)
Title: Convert String to CamelCase and PascalCase Language: C#
Description: Convert the string to CamelCase (lowerCamelCase) and PascalCase (UpperCamelCase) Views: 10983
Author: Mario Binder (www.biggle.de) Date Added: 10/25/2009
Copy Code  
1void Main() {
2    string a = "background color-red.brown";
3    string camelCase = ConvertCaseString(a, Case.CamelCase);
4    string pascalCase = ConvertCaseString(a, Case.PascalCase);
5}
6
7/// <summary>
8/// Converts the phrase to specified convention.
9/// </summary>
10/// <param name="phrase"></param>
11/// <param name="cases">The cases.</param>
12/// <returns>string</returns>
13static string ConvertCaseString(string phrase, Case cases)
14{
15    string[] splittedPhrase = phrase.Split(' ', '-', '.');
16    var sb = new StringBuilder();
17
18    if (cases == Case.CamelCase)
19    {
20        sb.Append(splittedPhrase[0].ToLower());
21        splittedPhrase[0] = string.Empty;
22    }
23    else if (cases == Case.PascalCase)
24        sb = new StringBuilder();
25
26    foreach (String s in splittedPhrase)
27    {
28        char[] splittedPhraseChars = s.ToCharArray();
29        if (splittedPhraseChars.Length > 0)
30        {
31            splittedPhraseChars[0] = ((new String(splittedPhraseChars[0], 1)).ToUpper().ToCharArray())[0];
32        }
33        sb.Append(new String(splittedPhraseChars));
34    }
35    return sb.ToString();
36}
37
38enum Case
39{
40    PascalCase,
41    CamelCase
42}