访问Vba - 反转字符串的内容

时间:2018-05-25 18:57:28

标签: vba access-vba ms-access-2010

我有一个名为str = "12345-1, 12345-2, 12345-3, 12345-4, 12345-5"的字符串我需要反转字符串,使其看起来像Sub rev() Dim str As String str = "12345-5, 12345-4, 12345-3, 12345-2, 12345-1" str = StrReverse(Trim(str)) 'turns out to be str = "1-54321 ,2-54321 ,3-54321 ,4-54321 ,5-54321" End Sub 我尝试过strReverse方法,它几乎做了我想要的......

{{1}}

但它最终扭转了整个字符串,应该已经猜到了。所以我想知道我是否应该使用正则表达式解析字符串并删除“12345-”然后将其反转并重新添加?我不太确定这是否是解决我问题的最佳方法。有谁知道我的问题的解决方案或能指出我正确的方向?感谢

2 个答案:

答案 0 :(得分:4)

使用Split然后循环遍历数组:

Sub rev()
    Dim str As String

    str = "12345-5, 12345-4, 12345-3, 12345-2, 12345-1"

    Dim strArr() As String
    strArr = Split(str, ",")

    str = ""

    Dim i As Long
    For i = UBound(strArr) To LBound(strArr) Step -1
        str = str & ", " & Trim(strArr(i))
    Next i

    str = Mid(str, 3)

    Debug.Print str
End Sub

答案 1 :(得分:0)

我会这样做:

Sub TestMe()

    Dim str As String
    str = "12345-5, 12345-4, 12345-3, 12345-2, 12345-1"
    str = StrReverse(str)

    Dim myArr As Variant
    myArr = Split(str, ",")

    Dim newString As String
    Dim myA As Variant

    For Each myA In myArr
        newString = newString & StrReverse(myA) & ","
    Next myA

    newString = Trim(Left(newString, Len(newString) - 1))
    Debug.Print newString

End Sub

获取此信息:

12345-1, 12345-2, 12345-3, 12345-4,12345-5

一般来说,这是一个非常流行的算法问题,谷歌过去常常会向初级开发人员提问。听起来像这样 - Efficiently reverse the order of the words (not characters) in an array of characters