Home
VB.NET
String Uppercase First Letter
This page was last reviewed on Sep 24, 2022.
Dot Net Perls
Uppercase first. This Function uppercases the first letter. It acts upon a VB.NET String. The value "test" becomes "Test". None of the other characters should be modified.
Function notes. If the first character is whitespace or a digit, it should not be affected. We introduce a custom method that uppercases the first letter.
Example. UppercaseFirstLetter receives a String and returns a String. In this function, we first test for null or empty parameters, and exit early in this case.
Next We call ToCharArray to convert the String into a mutable array of characters.
Then We use Char.ToUpper to uppercase the first letter, and we finally return a String instance built from the character array.
Char Array
Module Module1 Sub Main() Console.WriteLine(UppercaseFirstLetter("sam")) Console.WriteLine(UppercaseFirstLetter("perls")) 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
Sam Perls VB.NET
Function notes. This function, which uses the ToCharArray constructor, avoids allocations. In performance analysis, eliminating string allocations is often a clear win.
Warning This function has a limitation. It won't correctly process names that have multiple uppercase letters in them.
Dictionary
ToTitleCase. Instead of this custom implementation, you could use the ToTitleCase function. With ToTitleCase, every word is capitalized—this is a slightly different behavior.
String ToTitleCase
Summary. We learned one way you can uppercase only part of a string, such as the first letter. This method could be used to clean up poorly formatted character data.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 24, 2022 (rewrite).
Home
Changes
© 2007-2024 Sam Allen.