Following a
recent discussion I remembered this thread and how regular expressions can be used to simplify most things. Here's a new version with comments:
Code:
StringMod(string, method, param1 = "", param2 = "") {
If method = Only ; remove all characters not in param1 from string:
new := RegExReplace(string, "i)[^" . param1 . "]")
Else If method = Omit ; remove characters in param1 from string:
new := RegExReplace(string, "i)[" . param1 . "]")
Else If method = Flip ; flip string backwards:
Loop, % length := StrLen(string) ; loop for the length of the string
new .= SubStr(string, length - A_Index, 1) ; get character from the end going backwards
Else If method = Replace ; replace param1 with param2
new := RegExReplace(string, "i)" . param1, param2)
Else If RegExMatch(method, "Rot(?:ate)?(\d+)", rotN) ; for Rot13 and Rot47:
{
Loop, Parse, string ; for each character in the string:
new .= Chr((chr := Asc(A_LoopField)) + rotN1) - 94 * (chr > 126)) ; apply rotation transformation
; this increases the ASCII value of the character by the specified rotation amount
; if the value exceeds 126 (highest character) subtract by 94 (character range)
}
Else If method = Scramble ; rearrange characters in random order
{
new := RegExReplace(string, "(.)", "$1÷") ; delimit each character with '÷'
; this high-ASCII character is unlikely to exist in string, if it does it will be removed
Sort, new, Random Z D÷ ; randomly sort
new := RegExReplace(new, "÷") ; remove delimiter
}
Else If method = Bloat ; pad each character with param1 and param2:
new := RegExReplace(string, "(.)", param1 . "$1" . param2)
Else If method = Pattern ; return the number of times each character appears in the string:
{
unique := RegExReplace(string, "(.)", "$1÷") ; delimit each character with '÷' (like in 'Scramble')
Sort, unique, U Z D÷ ; remove duplicates
unique := RegExReplace(unique, "÷") ; remove delimiter
Loop, Parse, unique ; for each unique character in the string:
{
StringReplace, string, string, %A_LoopField%, , UseErrorLevel ; get the number of replacements
new .= A_LoopField . ErrorLevel ; store this alongside the character itself
}
}
Return, new ; return the modified string
}
Untested but I'm sure it works.