C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Here: We introduce a custom method that uppercases the first letter. A built-in method, ToTitleCase, is also available in the Framework.
Next: We call ToCharArray to convert the String into a mutable array of characters.
Then: We use the Char.ToUpper method to uppercase the first letter, and we finally return a new String instance built from the character array.
Char ArrayVB.NET program that uppercases first letter
Module Module1
Sub Main()
Console.WriteLine(UppercaseFirstLetter("sam"))
Console.WriteLine(UppercaseFirstLetter("Codex"))
Console.WriteLine(UppercaseFirstLetter(Nothing))
Console.WriteLine(UppercaseFirstLetter("VB.NET"))
End Sub
Function UppercaseFirstLetter(ByVal val As String) As String
' Test for nothing or empty.
If String.IsNullOrEmpty(val) Then
Return val
End If
' Convert to character array.
Dim array() As Char = val.ToCharArray
' Uppercase first character.
array(0) = Char.ToUpper(array(0))
' Return new string.
Return New String(array)
End Function
End Module
Output
Sam
Perls
VB.NET
Tip: In performance analysis, eliminating string allocations is often a clear win. Using ToCharArray here helps.
Warning: This function has a limitation. It won't correctly process names that have multiple uppercase letters in them.
So: The name "McChrystal" would be changed to "Mcchrystal" if the input string was "mcchrystal". This could be corrected with a Dictionary.
DictionaryNote: This method could be used to clean up poorly formatted character data, as from a text file or database.