-
Capitalize the First Letter of Each Word in a String
-
When working with text data in C#, one of the most common formatting tasks is converting a normal sentence into Title Case, where the first character of every word becomes uppercase while the remaining characters become lowercase.
Title Case is a text format where each word starts with an uppercase letter and the rest of the letters are lowercase.
Example:"hello world from c#"→ "Hello World From C#"
1. Using Basic C# Logic
This approach is perfect for beginners. In this:
- Split the sentence
- Capitalize the first letter
- Lowercase the rest
- Join everything back
Output:using System; class Program { static void Main() { string input = "hello world from c#"; string[] words = input.Split(' ', StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < words.Length; i++) { string w = words[i]; words[i] = char.ToUpper(w[0]) + w.Substring(1).ToLower(); } string result = string.Join(" ", words); Console.WriteLine(result); } }Hello World From C#
2. Using LINQ
This method is cleaner and more expressive. It uses
Split,Select, andstring.Join.
Output:using System; using System.Linq; class Program { static void Main() { string input = "hello world from c#"; var result = string.Join(" ", input.Split(' ', StringSplitOptions.RemoveEmptyEntries) .Select(word => char.ToUpper(word[0]) + word.Substring(1).ToLower())); Console.WriteLine(result); } }Hello World From C#
3. Using C# Built-in CultureInfo
C# also provides a built-in API that provides proper case conversion using the System.Globalization namespace.
Output:using System; using System.Globalization; class Program { static void Main() { string input = "hello world from c#"; TextInfo textInfo = CultureInfo.CurrentCulture.TextInfo; string result = textInfo.ToTitleCase(input.ToLower()); Console.WriteLine(result); } }Hello World From C#