Inverting every two Characters in a string

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
Attollere
Posts: 1
Joined: 25 May 2022, 04:36

Inverting every two Characters in a string

Post by Attollere » 25 May 2022, 04:54

I've been trying to figure out how to invert every two numbers in a string so for example if I have a string that is;

1a2b3c4d-5e6f-7g8h-9i1j
It should output
a1b2c3d4-e5f6-g7h8-i9j1

I've found a few posts about inverting everything however nothing for inverting every couple of characters while leaving the "-"

Any help would be appreciated

User avatar
mikeyww
Posts: 26857
Joined: 09 Sep 2014, 18:38

Re: Inverting every two Characters in a string

Post by mikeyww » 25 May 2022, 05:08

Welcome to this AutoHotkey forum!

Here's a start. Have a look at the documentation for details.

Code: Select all

str = 1a2b3c4d-5e6f-7g8h-9i1j
MsgBox, 64, Result, % "str  = " str "`n`nout = " invert(str)
; a1b2c3d4-e5f6-g7h8-i9j1

str = 1a2b3c4-5e6f-7g8h-9i1
MsgBox, 64, Result, % "str  = " str "`n`nout = " invert(str)

invert(str) {
 Loop, Parse, str
  Switch {
   Case A_LoopField = "-": out  .= char "-"        , char := ""
   Case char > ""        : out  .= A_LoopField char, char := ""
   Default               : char := A_LoopField
 }
 Return out char
}

sofista
Posts: 650
Joined: 24 Feb 2020, 13:59
Location: Buenos Aires

Re: Inverting every two Characters in a string

Post by sofista » 25 May 2022, 08:08

If it matters, a compact solution:

Code: Select all

str := "1a2b3c4d-5e6f-7g8h-9i1j"
For k, v in StrSplit(str, "-")
	str2 .= (!str2 ? "" : "-") RegExReplace(v, "(\w)(\w)", "$2$1")
MsgBox, % str2    ; output -> a1b2c3d4-e5f6-g7h8-i9j1

Post Reply

Return to “Ask for Help (v1)”