문제

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)
도움이 되었습니까?

해결책 2

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.

다른 팁

Just to mention this alternative

Dim currentCulture As CultureInfo = System.Threading.Thread.CurrentThread.CurrentCulture 
Dim titleCase = currentCulture.TextInfo.ToTitleCase(txtName.Text)
Console.WriteLine(titleCase)
Dim names() As String = titleCase.Split(" "c)
......

This method ensure the proper casing of the string respecting the current culture.
And doesn't require so many direct splitting and string concatenations with the inherent memory footprint. (Internally, a StringBuilder is used to manipulate the input string, with just one final ToString() to return the result)

Dim Name As String = "JOHN WAYNE DOE"
Name = Microsoft.VisualBasic.StrConv(Name, VbStrConv.ProperCase)

The will give the output "John Wayne Doe"

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top