试图将字符串拆分成相反的部分

时间:2014-01-11 17:07:49

标签: .net substring indexof

    Dim strFullName As String = txtFullName.Text

    Dim intFirstName As Integer = strFullName.IndexOf(" ")
    Dim strFirstName As String = strFullName.Substring(0, intFirstName)

    Dim intMiddleName As Integer = strFullName.IndexOf(" ", intFirstName + 1)
    Dim strMiddleName As String = strFullName.Substring(Name.IndexOf(" ") + 1)

    Dim intLastName As Integer = strFullName.LastIndexOf(" ", ((intFirstName) + (intMiddleName)))
    Dim strLastName As String = strFullName.Substring(2)
    txtReverseName.Text = (strLastName & "," & strFirstName & strMiddleName)

我正在尝试将字符串strFullName拆分为单个字符串,然后反转为Last,First Middle格式并输出到文本框。输出不正确,for example。如果有人有任何想法来解决这种情况我一直认为这将是伟大的。

2 个答案:

答案 0 :(得分:1)

    Dim x As String = "a b c"
    Dim array = x.Split(" ")
    Dim y = array(2) + " " + array(0) + " " + array(1)

产地:

“c a b”

答案 1 :(得分:0)

在您输入使用IndexOf之后,您可以尝试使用此代码。

Dim strFullName As String = txtFullName.Text
Dim strMiddleName As String = String.Empty
Dim strFirstName As String = string.Empty
Dim strLastName As String = string.Empty

' Search the first space position '
Dim spacePos As Integer = strFullName.IndexOf(" ")

' Check if user has inserted a space (spacePos is equal to -1 otherwise) '
if spacePos >= 0 Then
    ' Extract the string from the beginning to the space found '
    strFirstName = strFullName.Substring(0, spacePos)
    ' Now check if there is another space but starting from a position after the first one'
    Dim intMiddleName As Integer = strFullName.IndexOf(" ", spacePos + 1)
    ' Again check if there is a second space '
    if intMiddleName >= 0 Then
      ' Get the middle from a position after the first one and for a length of chars
      ' given by the second space position less the first space position '
      strMiddleName = strFullName.Substring(spacePos + 1, intMiddleName - spacePos)
      ' Advance to the next non space char '
      spacePos = intMiddleName + 1
    end if
    ' Take the last part of the string from whatever position the spacePos variable points to'
    strLastName = strFullName.Substring(spacePos)

    ' Rebuild as desired '
    txtReverseName.Text = (strLastName & "," & strFirstName & " " & strMiddleName)
End If

请记住,此代码仍然非常弱,因为您的用户可以使用该文本框创建数字(例如连续写两个空格)