PDA

View Full Version : Example: Get Reverse of String


Intrigued
12-13-2006, 08:25 PM
-- A function that will reverse and return a string of characters
function fReverseCharacters(argString)
strDataTypedIn = Dialog.Input("Enter some data", "Type in a line of data", "", MB_ICONINFORMATION)

numDataTypedInLength = String.Length(strDataTypedIn)

strDataReturned = ""

for n = 0, numDataTypedInLength do
strCharacter = String.Mid(strDataTypedIn, numDataTypedInLength-n, 1)
strDataReturned = strDataReturned..strCharacter
end
return strDataReturned
end

-- Testing the function
Dialog.Message("Data Returned, but in reverse order", fReverseCharacters("Hi from Intrigued!"))

Lorne
12-14-2006, 02:14 AM
I was going to suggest string.reverse, but I think that's only available in a newer version of lua (5.1?).

So instead I'll suggest two alternative versions using older built-in lua functions for educational purposes:

function GetReversed(str)
local reversed = "";
for i = string.len(str), 1, -1 do
reversed = reversed..string.sub(str,i,i);
end
return reversed;
end

function GetReversed(str)
local reversed = "";
for i = 1, string.len(str) do
reversed = string.sub(str,i,i)..reversed;
end
return reversed;
end

(The first version is possibly more efficient, but I couldn't say for sure without timing it.)

Intrigued
12-14-2006, 07:56 AM
Thanks Lorne.

yosik
12-15-2006, 04:22 AM
Thank you both.
One of the uses of this function could be with Right to Left languages. Although AMS supports them, it can come handy for the use with other apps that do not.

Thanks

Yossi

Intrigued
12-15-2006, 01:23 PM
No problem Yosik. I'm glad they will come in handy sooner or later.

:yes