Search code examples
vb.netcasetolowertoupper

using toupper and tolower in visual basic


Trying to get this to change the case of the first letter of the parsed strings segments. So if a user enters "JOHN WAYNE DOE" in txtName then it would display "John Wayne Doe" I entered it the way it shows it in the book but the message box displays the parsed string however it was entered so in the above example the return is "JOHN WAYNE DOE" I figure its a logic error since I am known to do that a lot just have no idea where i made the error.

    Dim name As String = txtName.Text
    name = name.Trim
    Dim names() As String = name.Split(CChar(" "))
    Dim firstName As String = names(0)
    Dim middleName As String = names(1)
    Dim lastName As String = names(2)

    Dim firstLetters1 As String = firstName.Substring(0, 1).ToUpper
    Dim otherletters1 As String = firstName.Substring(1).ToLower

    Dim firstLetters2 As String = middleName.Substring(0, 1).ToUpper
    Dim otherletters2 As String = middleName.Substring(1).ToLower

    Dim firstletters3 As String = lastName.Substring(0, 1).ToUpper
    Dim otherletters3 As String = lastName.Substring(1).ToLower

    MessageBox.Show("First Name: " & firstName & vbCrLf & "Middle Name: " & middleName & vbCrLf & "Last Name: " & lastName)

Solution

  • Try this:

    MessageBox.Show(_
        "First Name: " & firstLetters1 & otherletters1 & vbCrLf & _
        "Middle Name: " & firstLetters2 & otherletters2 & vbCrLf & _ 
        "Last Name: " & firstLetters3 & otherletters3)
    

    String is immutable class, your ToUpper and ToLower calls create new instances. In the message box you are passing the old unprocessed instances.


    Update Alternatively, you can use our old call:

     MessageBox.Show("First Name: " & firstName & vbCrLf & "Middle Name: " & middleName & vbCrLf & "Last Name: " & lastName)
    

    as long as you do this before:

    firstName = firstLetters1 & otherletters1
    middleName = firstLetters2 & otherletters2
    lastName = firstLetters3 & otherletters3
    

    This might get you a better idea on how string's immutability works.