在visual basic中使用toupper和tolower

时间:2013-04-05 08:38:39

标签: vb.net case tolower toupper

试图让它改变解析后的字符串段的第一个字母的大小写。因此,如果用户在txtName中输入“JOHN WAYNE DOE”,那么它将显示“John Wayne Doe” 我按照它在书中显示它的方式输入它,但是消息框显示已解析的字符串,但是输入了所以在上面的示例中返回的是“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)

3 个答案:

答案 0 :(得分: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()返回结果)

答案 1 :(得分: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

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

答案 2 :(得分:0)

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

将输出“John Wayne Doe”