First Letter In Uppercase in C#

Strings sometimes have lowercase first letters. Uppercasing the first letter is often necessary. Learn how to make a string's first letter uppercase in C# and .NET.

Strings sometimes have lowercase first letters. Uppercasing the first letter is often necessary for example, a name. The code samples are examples of how to make a string's first letter uppercase using String.Substring() method of C# and .NET.
 
The string has its first letter uppercased. It is then returned with the remaining part unchanged. This is the functionality of the ucfirst function from PHP and Perl. And strings with multiple words can be changed to title case.
 
First Example
 
Input
 
amit patel
ranna patel
  1. public static string FirstCharToUpper(string s)  
  2. {  
  3. // Check for empty string.  
  4. if (string.IsNullOrEmpty(s))  
  5. {  
  6. return string.Empty;  
  7. }  
  8. // Return char and concat substring.  
  9. return char.ToUpper(s[0]) + s.Substring(1);  
  10. }  
OUTPUT
 
Amit patel
Ranna patel
 
Secont Example
 
Input
 
amit patel
ranna patel
  1. public static string FirstCharToUpper(string value)  
  2. {  
  3. char[] array = value.ToCharArray();  
  4. // Handle the first letter in the string.  
  5. if (array.Length >= 1)  
  6. {  
  7. if (char.IsLower(array[0]))  
  8. {  
  9. array[0] = char.ToUpper(array[0]);  
  10. }  
  11. }  
  12. // Scan through the letters, checking for spaces.  
  13. // ... Uppercase the lowercase letters following spaces.  
  14. for (int i = 1; i < array.Length; i++)  
  15. {  
  16. if (array[i - 1] == ' ')  
  17. {  
  18. if (char.IsLower(array[i]))  
  19. {  
  20. array[i] = char.ToUpper(array[i]);  
  21. }  
  22. }  
  23. }  
  24. return new string(array);  
  25. }  
OUTPUT
 
Amit Patel
Ranna Patel