How to Capitalize the First Letter of All Words in a string in C# ?


Often we need to capitalize the first letters of some word or some text (for example when we want to display users name or city name etc).

Since string class does not have a method to do this we could think that there is no built-in solution in C# for this problem.

Here i am giving two solution for this problem.

Solution 1-

We can use  ToTitleCase method of TextInfo class in System.Globalization namespace  for this problem.

    public static string Capitalize(string value)
    {
        return       System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(value);
    }

Solution 2-

The below method will return  Capitalize Words.

   public static string CapitalizeWords(string value)
    {
        if (value == null)
            throw new ArgumentNullException("value");
        if (value.Length == 0)
            return value;

        StringBuilder result = new StringBuilder(value);
        result[0] = char.ToUpper(result[0]);
        for (int i = 1; i < result.Length; ++i)
        {
            if (char.IsWhiteSpace(result[i - 1]))
                result[i] = char.ToUpper(result[i]);
        }
        return result.ToString();
    }
Tags: , ,

Join Us!