Tuesday, June 27, 2006

VB: Change String Case

A real simple question came across my way. The question was “How can I change case with a Visual Basic string?”

Visual Basic provides two functions for changing case, Ucase and Lcase. Consider the following example. Here, I am going to traverse through a string, and switch the case of each individual character. In function 1, I am going to use a Byte array and switch the case of each element in the array. In function 2, I will build a temp string using the VB string function MID. The string is in a textbox called Text1.

Public Sub Function_1()
    Dim ary() As Byte
    Dim x As Integer
    
    'Set the array size to equal the size of our string. Use lenb to get the actual byte size
    ReDim ary(LenB(Text1.Text))
    
    'Assign the string to the byte array
    ary = Text1.Text
    
    'For the size of the array, go through each character and change the case
    'Remember, this is a byte array, so it compares using numbers, so use the
    'asc function to get the ascii value of the characters to compare against.
    For x = LBound(ary) To UBound(ary)
        If (ary(x) >= Asc("a")) And (ary(x) <= Asc("z")) Then
            'using the chr and asc function, change to a character, change the case
            'and then switch back to an ASCII number.
            ary(x) = Asc(UCase(Chr(ary(x))))
        Else
            If (ary(x) >= Asc("A")) And (ary(x) <= Asc("Z")) Then
                ary(x) = Asc(LCase(Chr(ary(x))))
            End If
        End If
    Next
    
    'Display the result
    MsgBox ary, vbOKOnly
End Sub

Public Sub Function_2()
    Dim temp As String
    Dim x As Integer
    
    For x = 1 To Len(Text1.Text)
        If (Asc(Mid(Text1.Text, x, 1)) >= Asc("a")) And (Asc(Mid(Text1.Text, x, 1)) <= Asc("z")) Then
            temp = temp & UCase(Mid(Text1.Text, x, 1))
        Else
            If (Asc(Mid(Text1.Text, x, 1)) >= Asc("A")) And (Asc(Mid(Text1.Text, x, 1)) <= Asc("Z")) Then
                temp = temp & LCase(Mid(Text1.Text, x, 1))
            Else
                temp = temp & Mid(Text1.Text, x, 1)
            End If
        End If
    Next
    
    MsgBox temp, vbOKOnly
End Sub

No comments: