2

试图让它改变解析字符串段的第一个字母的大小写。因此,如果用户在 txtName 中输入“JOHN WAYNE DOE”,那么它将显示“John Wayne Doe” return 是“JOHN WAYNE DOE” 我认为这是一个逻辑错误,因为众所周知我经常这样做,只是不知道我在哪里犯了错误。

    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)
4

3 回答 3

5

只是提到这个替代方案

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)
......

此方法确保字符串的正确大小写尊重当前区域性。
并且不需要如此多的直接拆分和字符串连接以及固有的内存占用。(在内部,一个 StringBuilder 用于操作输入字符串,最后只有一个 ToString() 来返回结果)

于 2013-04-05T09:00:25.777 回答
0

试试这个:

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

String 是不可变类,您的ToUpperToLower调用会创建新实例。在消息框中,您传递的是旧的未处理实例。


更新 或者,您可以使用我们的旧电话:

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

只要你之前这样做:

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

这可能会让您更好地了解字符串的不变性是如何工作的。

于 2013-04-05T08:43:05.373 回答
0
Dim Name As String = "JOHN WAYNE DOE"
Name = Microsoft.VisualBasic.StrConv(Name, VbStrConv.ProperCase)

将给出输出“John Wayne Doe”

于 2013-04-05T10:31:16.993 回答