Capitalize first letter of a string in C#
This post will discuss how to capitalize the first letter of a string in C#.
The idea is to extract the first character from the string, convert it to uppercase using the ToUpper() method, and append it with the remaining string. You can extract the substring starting from the second character till its end using the Substring() method.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
using System; public static class StringExtensions { public static string UpperFirstChar(this string input) { if (string.IsNullOrEmpty(input)) { return null; } return char.ToUpper(input[0]) + input.Substring(1); } } public class Example { public static void Main() { string s = "hello"; s = s.UpperFirstChar(); Console.WriteLine(s); // Hello } } |
Alternatively, you can convert the string to a character array and convert the first character to uppercase. Then, construct a new string using the string constructor.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
using System; public static class StringExtensions { public static string UpperFirstChar(this string input) { if (string.IsNullOrEmpty(input)) { return null; } char[] chars = input.ToCharArray(); chars[0] = char.ToUpper(chars[0]); return new string(chars); } } public class Example { public static void Main() { string s = "hello"; s = s.UpperFirstChar(); Console.WriteLine(s); // Hello } } |
That’s all about capitalizing the first letter of 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 :)