我遇到了为Visual Basic 2012课程分配的问题。说明如下。到目前为止,我只显示输入的第一个名称,而不是其他任何名称。如何使其显示所请求序列中的名字和姓氏?
字符串问题:在文本框中输入您的姓名。取名并将其显示在显示姓氏,名字的标签框中。
文本框条目:Jane Doe
标签盒:Doe,Jane
我到目前为止的代码如下。谢谢你的帮助!
Private Sub btndisplay_Click(sender As Object, e As EventArgs) Handles btndisplay.Click
Dim fullname As String
Dim firstname As String
Dim indexnum As Integer
Dim lastname As String
fullname = fulltextbox.Text
indexnum = fullname.IndexOf(" ")
firstname = fullname.Substring(0, indexnum)
firstlabel.Text = firstname
fulltextbox.Focus()
End Sub
Private Sub fulltextbox_TextChanged(sender As Object, e As EventArgs)
firstlabel.Text = String.Empty
fulltextbox.SelectAll()
End Sub
Private Sub btnexit_Click(sender As Object, e As EventArgs) Handles btnexit.Click
Me.Close()
End Sub
答案 0 :(得分:0)
首先确定空间的位置,以确保您走在正确的轨道上:
indexnum = fullname.IndexOf(" ")
现在基于此索引,您可以将字符串拆分为两个字符串firstname
和lastname
:
firstname = fullname.Substring(0, indexnum)
lastname = fullname.Substring(indexnum+1)
您需要使用indexnum+1
,而不是indexnum
,否则您将包含间距字符。
最后,您使用string concatenation operator (&
):
firstlabel.Text = lastname & ", " & firstname
最终方法如下:
Private Sub btndisplay_Click(sender As Object, e As EventArgs) Handles btndisplay.Click
Dim fullname As String
Dim firstname As String
Dim indexnum As Integer
Dim lastname As String
fullname = fulltextbox.Text
indexnum = fullname.IndexOf(" ")
firstname = fullname.Substring(0, indexnum)
lastname = fullname.Substring(indexnum+1)
firstlabel.Text = lastname & ", " & firstname
fulltextbox.Focus()
End Sub
答案 1 :(得分:0)
注意,如果您使用中间名字缩写,这将无法奏效。另外,我会从fulltextbox.SelectAll()
fulltextbox_TextChanged
Private Sub btndisplay_Click(sender As Object, e As EventArgs) Handles btndisplay.Click
Dim Names() As String = fulltextbox.Text.Split(" "c)
If Names.Count = 2 Then
firstlabel.Text = Names(1) + ", " + Names(0)
ElseIf Names.Count = 0 Then
MessageBox.Show("Please enter name.")
Else
MessageBox.Show("Invalid Nmae entered.")
End If
fulltextbox.Text = ""
End Sub