Archive: How to Reverse a String?


How to Reverse a String?
  Hi, here

I need to Reverse a String, for example, transfer string to gnirts

How could i manage it? :stare::stare:

thx


Use StryCpy in a loop...

Section
StrCpy $0 "string" #init
StrCpy $2 "" #init
Loop:
StrCmp $0 "" Done #done yet?
StrCpy $1 $0 1 -1 #get last char of $0
StrCpy $2 "$2$1" #append last char to $2
StrCpy $0 $0 -1 #remove last char from $0
Goto Loop #loop
Done:
MessageBox MB_OK "$2"
SectionEnd

StrLen $0 $YourString
StrCpy $1 ""
loop:
IntOp $0 $0 - 1
${If} $0 == "-1"
goto end
${EndIf}
StrCpy $2 $YourString 1 $0
StrCpy $1 "$1$2"
goto loop
end:

Not tested, but you get the idea.


Edit: Doh, beat me to it. :) Also, funny how our solutions are quite different but the number of OPs is exactly the same. I wonder if an intop is faster than a strcpy?


A native C implementation that just swaps s[i] and s[len-i] inplace would probably beat both implementations :)

[EDIT]

Here we go:
http://code.google.com/p/mulder/sour...2FStdUtils.cpp


This is working:

!define StrRev "!insertmacro _StrRev"

>!macro _StrRev _STR_
Push$1 ;; Reversed string
Push$2 ;; String Len / Counter
Push$3 ;; Current character

StrCpy$1 ""
StrLen $2 "${_STR_}"

loop:
IntCmp $2 0 endloop
IntOp$2 $2 - 1
StrCpy$3 "${_STR_}" 1 $2
StrCpy$1 "$1$3"
Goto loop
endloop:

Pop $3
Pop$2
Exch$1
Pop${_STR_}
!macroend
>

StrCpy $1 "1234567"

>${StrRev} $1
MessageBox MB_OK "$1"
To put the reversed string in another variable, edit 2 lines:
!macro _StrRev _STR_ _REV_
...
Pop ${_REV_}


[EDIT]

Function version:

"!insertmacro _StrRev"

>!macro _StrRev _STR_
Push${_STR_}
Call __StrRev
Pop${_STR_}
!macroend

>Function __StrRev
Exch$0 ;; The orig string
Push$1 ;; Reversed string
Push$2 ;; String Len / Counter
Push$3 ;; Current character

StrCpy$1 ""
StrLen $2 "$0"

loop:
IntCmp $2 0 endloop
IntOp$2 $2 - 1
StrCpy$3 "$0" 1 $2
StrCpy$1 "$1$3"
Goto loop
endloop:

Pop $3
Pop$2
Exch$1
Exch
Pop$0
FunctionEnd
>