Format a string to proper case with C#

PsychoCoder 2 Tallied Votes 2K Views Share

This snippet takes a string as input and formats it to proper case

/// <summary>
/// method to convert a string to proper case 
/// </summary>
/// <param name="str">value we want converted</param>
/// <returns></returns>
public string FormatProperCase(string str)
{
    // if not value is provided throw an exception
    if (string.IsNullOrEmpty(str))
        throw new ArgumentException("A null value cannot be converted", str);
 
    //if the stirng is less than 2 characters return it upper case
    if (str.Length < 2) 
        return str.ToUpper();
 
    //let's start with the first character (make upper case)
    string converted = str.Substring(0, 1).Trim().ToUpper();
 
    //now loop through the rest of the string converting where needed
    for (int i = 1; i < str.Length; i++)
    {
        converted = 
            (Char.IsUpper(str[i])) ? 
            converted += " " : 
            converted += str[i];
    }
 
    //return the formatted string
    return converted;
}
lipasion 0 Newbie Poster
/// <summary>
        /// method to convert a series of string to proper case 
        /// </summary>
        /// <param name="str">value we want converted</param>
        /// <returns></returns>
        public static string FormatProperCase(string str)
        {
            // if not value is provided throw an exception
            if (string.IsNullOrEmpty(str)) return string.Empty;

            //if the stirng is less than 2 characters return it upper case
            if (str.Length < 2) return str.ToUpper();

            string[] strlst = str.Split(new char[] { ' ' });
            foreach (string s in strlst)
            {
                int i = 0;
                string sout = string.Empty;
                foreach (char c in s)
                {
                    sout += (i == 0 ? Char.ToUpper(c) : Char.ToLower(c));
                    i++;
                }
                str = str.Replace(s, sout);
            }
            return str;
        }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.