C# Program to Capitalize First Letter of Each Word
System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(string.ToLower()) to capitalize the first letter of each word in C#.Examples
How to Think About It
Algorithm
Code
using System; using System.Globalization; class Program { static void Main() { string input = "hello world from c#"; string result = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(input.ToLower()); Console.WriteLine(result); } }
Dry Run
Let's trace the input "hello world from c#" through the code.
Input string
input = "hello world from c#"
Convert to lowercase
input.ToLower() = "hello world from c#" (already lowercase)
Capitalize first letter of each word
ToTitleCase("hello world from c#") = "Hello World From C#"
Print result
Output: "Hello World From C#"
| Step | Operation | Result |
|---|---|---|
| 1 | Input string | hello world from c# |
| 2 | ToLower() | hello world from c# |
| 3 | ToTitleCase() | Hello World From C# |
| 4 | Print output | Hello World From C# |
Why This Works
Step 1: Normalize case
Converting the string to lowercase ensures that all letters start from a consistent state before capitalizing.
Step 2: Capitalize words
The ToTitleCase method changes the first letter of each word to uppercase automatically.
Step 3: Output result
The final string has each word's first letter capitalized, making it look neat and readable.
Alternative Approaches
using System; class Program { static void Main() { string input = "hello world from c#"; string[] words = input.Split(' '); for (int i = 0; i < words.Length; i++) { if (words[i].Length > 0) words[i] = char.ToUpper(words[i][0]) + words[i].Substring(1).ToLower(); } string result = string.Join(" ", words); Console.WriteLine(result); } }
using System; using System.Text.RegularExpressions; class Program { static void Main() { string input = "hello world from c#"; string result = Regex.Replace(input.ToLower(), "\\b[a-z]", m => m.Value.ToUpper()); Console.WriteLine(result); } }
Complexity: O(n) time, O(n) space
Time Complexity
The program processes each character once when converting case and capitalizing, so it runs in linear time relative to string length.
Space Complexity
A new string is created for the output, so space grows linearly with input size.
Which Approach is Fastest?
Using ToTitleCase is efficient and concise; manual splitting or regex adds overhead and complexity.
| Approach | Time | Space | Best For |
|---|---|---|---|
| ToTitleCase method | O(n) | O(n) | Simple and fast capitalization |
| Manual split and capitalize | O(n) | O(n) | More control over each word |
| Regex replacement | O(n) | O(n) | Flexible pattern matching |
ToTitleCase on a lowercase string to reliably capitalize each word's first letter.