Skip to main content

Convert strings between Pascal case, camel case, and proper case in C#. This example uses string extensions to convert strings between these three formats.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

public static class StringExtensions
{
    // Convert the string to Pascal case.
    public static string ToPascalCase(this string the_string)
    {
        // If there are 0 or 1 characters, just return the string.
        if (the_string == null) return the_string;
        if (the_string.Length < 2) return the_string.ToUpper();

        // Split the string into words.
        string[] words = the_string.Split(
            new char[] { },
            StringSplitOptions.RemoveEmptyEntries);

        // Combine the words.
        string result = "";
        foreach (string word in words)
        {
            result +=
                word.Substring(0, 1).ToUpper() +
                word.Substring(1);
        }

        return result;
    }

    // Convert the string to camel case.
    public static string ToCamelCase(this string the_string)
    {
        // If there are 0 or 1 characters, just return the string.
        if (the_string == null || the_string.Length < 2) return the_string;

        // Split the string into words.
        string[] words = the_string.Split(
            new char[] { },
            StringSplitOptions.RemoveEmptyEntries);

        // Combine the words.
        string result = words[0].ToLower();
        for (int i = 1; i < words.Length; i++)
        {
            result +=
                words[i].Substring(0, 1).ToUpper() +
                words[i].Substring(1);
        }

        return result;
    }

    // Capitalize the first character and add a space before
    // each capitalized letter (except the first character).
    public static string ToProperCase(this string the_string)
    {
        // If there are 0 or 1 characters, just return the string.
        if (the_string == null) return the_string;
        if (the_string.Length < 2) return the_string.ToUpper();

        // Start with the first character.
        string result = the_string.Substring(0, 1).ToUpper();

        // Add the remaining characters.
        for (int i = 1; i < the_string.Length; i++)
        {
            if (char.IsUpper(the_string[i])) result += " ";
            result += the_string[i];
        }

        return result;
    }
}