i.Newbie
i.Newbie

Reputation: 29

Reverse string message from end to start by 2 chars

String:

00000C0065060061

Should look like:

61000665000C0000

What i tried:

   dim data as string
   data = "00000C0065060061"
   ReverseString(data)           ' calling a function

   Function ReverseString(ByVal sText As String) As String
    Dim lenText As Long, lPos As Long
    If Len(sText) = 0 Then Exit Function
    lenText = Len(sText)
    ReverseString = Space(lenText)
    For lPos = lenText To 1 Step -2
        Try
            If lPos > 0 Then Mid(ReverseString, lenText - lPos + 1, 2) = Mid(sText, lPos - 1, 2)
            If lPos = 0 Then Mid(ReverseString, lenText - lPos + 1, 2) = Mid(sText, lPos, 2)
        Catch argEx As ArgumentException
        End Try
    Next lPos
End Function

I always have a System.ArgumentException, therefore i catch it, and seems it slows down my programm and it becomes laggy. Code above seems correct, any suggestions?

Upvotes: 0

Views: 149

Answers (2)

Youssef13
Youssef13

Reputation: 4944

Based on comments, You can try this one line :)

Dim Output As String = String.Join("", Regex.Matches("00000C0065060061", ".{2}").Cast(Of Match).Reverse().Select(Function(M As Match) M.Value).ToArray())

Don't forget:

Imports System.Text.RegularExpressions

To explain the above code:

  1. The regex matches each 2 characters and you will have MatchCollection, The first Match in the collection should have first two characters, the second match should have second two characters, etc

  2. The MatchCollection will be converted to IEnumerable of Match which will be reversed

  3. It will be then converted to IEnumerable of String and then to an array.
  4. The array will be joined together to make the output string.

Note: This will work only on .NET Framework 3.5 or higher, will NOT work on .NET Framework 3.0 or 2.0

Upvotes: 0

kiLLua
kiLLua

Reputation: 471

Here, Try this:

Private Function Reverse(ByVal str As String) As String
    Dim rev As String = ""
    Dim strLen As Integer = Len(str)
    Dim index = strLen - 1
    For i As Integer = 0 To strLen - 1
        Try
            rev = rev + str(index - 1) + str(index)
        Catch ex As Exception

        End Try
        index -= 2
    Next
    Return rev
End Function

EDIT:

Private Function Reverse(ByVal str As String) As String
    Dim rev As String = ""
    Dim index = Len(str) - 1
    Do While (index > 0)
        rev = rev + str(index - 1) + str(index)
        index -= 2
    Loop
    Return rev
End Function

Upvotes: 1

Related Questions