How do I capitalize each word in a string?
Category: System, viewed: 2K time(s).
This example show you how to use the System.Globalization.TextInfo class to capitalize each word in a string. This class provide a method named ToTitleCase(str) that capitalize the words.
Let's see an example below:
using System;
using System.Globalization;
namespace Kodecsharp.Example.System {
class WordCapitalize {
static void Main(string[] args) {
string str = "The quick brown fox jumps over the lazy dog.";
Console.WriteLine("str = " + WordCapitalize.capitalize(str, "en-US"));
Console.WriteLine("str = " + WordCapitalize.capitalize(str));
Console.ReadLine();
}
/// <summary>
/// Capitalize using a specified culture.
/// </summary>
static string capitalize(string str, string culture) {
TextInfo ti = new CultureInfo(culture, false).TextInfo;
return ti.ToTitleCase(str);
}
/// <summary>
/// Capitalize using system default culture information.
/// </summary>
static string capitalize(string str) {
return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str);
}
}
}
Here are the result of the program:
str = The Quick Brown Fox Jumps Over The Lazy Dog.
str = The Quick Brown Fox Jumps Over The Lazy Dog.