Capitalize first letter of each word in a string in C#
This article illustrates the different techniques to capitalize the first letter of each word in a string in C#.
1. Using TextInfo.ToTitleCase() method
To convert a string to a title case, you can use the TextInfo.ToTitleCase() method. In the title case, all words are capitalized. Note that you need to include the System.Globalization namespace. The following sample illustrates its usage.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Globalization; public class Example { public static void Main() { string s = "hello world"; TextInfo textInfo = CultureInfo.CurrentCulture.TextInfo; string titleCase = textInfo.ToTitleCase(s); Console.WriteLine(titleCase); // Hello World } } |
The above code will ignore the strings in all caps, such as “HTTPS”. In order to capitalize only the first character in the string and lower the rest, you can do like:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Globalization; public class Example { public static void Main() { string s = "Use HTTPS"; TextInfo textInfo = CultureInfo.CurrentCulture.TextInfo; string titleCase = textInfo.ToTitleCase(s.ToLower()); Console.WriteLine(titleCase); // Use Https } } |
2. Using Regex
You can also use regular expressions to capitalize the first letter of each word in a string. Here’s what the code would look like:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Text.RegularExpressions; public class Example { public static void Main() { string s = "hello,welcome to techie delight"; string titleCase = Regex.Replace(s, @"((^\w)|(\s|\p{P})\w)", match => match.Value.ToUpper()); Console.WriteLine(titleCase); // Hello,Welcome To Techie Delight } } |
That’s all about capitalizing the first letter of each word in a string in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)