Capitalizing a string is a rather trivial task in C#. There are 2 ways to approach single word capitalization where each method includes 3 steps. Method 1 uses only strings and string methods while method 2 treats the letter to be capitalized as a char.
Method 1:
- Get the first character as a string ( stringToCapitalize.Substring(0,1) )
- Transform the first character to uppercase ( stringToCapitalize.Substring(0,1).ToUpper() )
- Append the rest of the string ( stringToCapitalize.Substring(0,1).ToUpper() + stringToCapitalize.Substring(1) )
1 2 3 4 5 6 7 8 9 10 | public static string Capitalize(string toCapitalize) { try { if(toCapitalize.Length > 1) { toCapitalize = toCapitalize.Substring(0, 1).ToUpper() + toCapitalize.Substring(1); } } catch(Exception ex) { ExceptionHandling.ExceptionLogging(ex, "Error:Capitalize."); } return toCapitalize; } |
Method 2:
- Get the first character as a char ( stringToCapitalize[0] )
- Transform the first character to uppercase using the char.toUpper method ( char.toUpper(stringToCapitalize[0]) )
- Append the rest of the string ( char.toUpper(stringToCapitalize.Substring[0]) + stringToCapitalize.Substring(1) )
1 2 3 4 5 6 7 8 9 10 | public static string Capitalize(string toCapitalize) { try { if(toCapitalize.Length > 1) { toCapitalize = char.ToUpper(toCapitalize[0]) + toCapitalize.Substring(1); } } catch(Exception ex) { ExceptionHandling.ExceptionLogging(ex, "Error:Capitalize."); } return toCapitalize; } |
Using either of these methods you could create an extension method as well. Something like this:
1 2 3 4 5 6 7 8 9 10 | public static class MyExtensions { public static string Capitalize(this String toCapitalize) { if(toCapitalize.Length > 1) { toCapitalize = toCapitalize.Substring(0, 1).ToUpper() + toCapitalize.Substring(1); } return toCapitalize; } } |