Recipe 5.7. Converting a String's CaseProblemYou want to convert a string to all uppercase, all lowercase, or mixed case (with only the first letter of each word in uppercase). SolutionSample code folder: Chapter 05\MixedCase The string methods ToUpper() and ToLower() make it easy to convert strings to upper-and lowercase, and a short special-purpose function can perform the mixed conversion. You can also use the standard Visual Basic UCase() and LCase() methods. To mix-case a string, use Visual Basic's StrConv() function. DiscussionChanging strings to upper- or lowercase is standard Visual Basic fare: ' ----- To upper case. newString = oldString.ToUpper() newString = UCase(oldString) ' ----- To lower case. newString = oldString.ToLower() newString = LCase(oldString) To convert the string to mixed or "proper" case, use one of the conversion methods included in the StrConv() function: newString = StrConv(oldString, VbStrConv.ProperCase) This function converts the first letter of each word to uppercase, making every other letter lowercase. Its rules are pretty basic, and it doesn't know about special cases. If you need to correctly capitalize names such as "MacArthur," you have to write a custom routine. The following code provides the start of a routine using an algorithm that works much like the StrConv() function. It assumes that space characters separate each word: Public Function MixedCase(ByVal origText As String) As String ' ----- Convert a string to "proper" case. Dim counter As Integer Dim textParts() As String = Split(origText, " ") For counter = 0 To textParts.Length - 1 If (textParts(counter).Length > 0) Then _ textParts(counter) = _ UCase(Microsoft.VisualBasic.Left( _ textParts(counter), 1)) & _ LCase(Mid(textParts(counter), 2)) Next counter Return Join(textParts, " ") End Function The code splits up the original text into an array at space-character boundaries using the Split() function. It then processes each word separately and merges them back together with the Join() method. Figure 5-5 shows the results of various conversions on a string, including a conversion using the custom MixedCase() function. Notice that "albert" is not capitalized in the mixed-case string. This is because the two leading dashes are considered to be part of this word, based on how the Split() function separated the words at space-character locations. Figure 5-5. The original string before and after various case conversions
See AlsoRecipe 5.44 discusses the Split() function and the Split() method. |