capitalizes the first letter of every word - CSharp System

CSharp examples for System:String Case

Description

capitalizes the first letter of every word

Demo Code


using System.Text.RegularExpressions;
using System.Text;
using System.Globalization;
using System.Collections.Generic;
using System;/*  w  w w. ja v a 2s .c om*/

public class Main{
        //Very much like the GetTitle function, capitalizes the first letter of every word
        //Additional function is, mcdonald -> McDonald, machenry -> MacHenry
        //Credits to ShutlOrbit (http://www.thirdstagesoftware.com) from CodeProject
        public static string GetNameCasing(string input)
        {
            string[] words = input.Split(new char[] { ' ' });

            for (int i = 0; i < words.Length; i++)
            {
                if (words[i].Length > 0)
                {
                    words[i] = words[i].Substring(0, 1).ToUpper() + words[i].Substring(1);
                    if (words[i].StartsWith("Mc") && words[i].Length > 2)
                        words[i] = words[i].Substring(0, 2) + words[i].Substring(2, 1).ToUpper() + words[i].Substring(3);
                    else if (words[i].StartsWith("Mac") && words[i].Length > 3)
                        words[i] = words[i].Substring(0, 3) + words[i].Substring(3, 1).ToUpper() + words[i].Substring(4);
                }
            }
            return String.Join(" ", words);
        }
}

Related Tutorials