Reversing text

This lesson will explain how to reverse a piece of text.

The reversed function

The reversed function takes one parameter, pText, reverses it character by character and returns the backwards version of the original string.

get reversed("A man, a canal, Panama")
put reversed(it) into field "Reversed Text"
answer reversed(field "Answer")

The handler uses a repeat control structure to scan each character in the string. Unlike a typical repeat loop, this one doesn't start at the first character and go to the last. Instead, it uses the repeat...down to form to start at the last character and go back to the first.

The handler places each character at the end of a variable called tReversedString. Because the repeat loop in this handler goes backwards, the tReversedString variable ends up holding the same characters as the original string, but in reverse order. When the repeat loop finishes, the tReversedString variable is returned as the value of the function.

You can use similar handlers to reverse the words or lines in a string. In fact, using the itemDelimiter property, you can reverse the items in a string, using any character as the item delimiter.

The reversed function code

function reversed pString
	local tReversedString
   
	repeat with tChar = the length of pString down to 1
		put char tChar of pString after tReversedString
	end repeat
	
	return tReversedString
end reversed

A note on efficiency

You might initially think that using the repeat for each form of the repeat control structure would be faster, since in general, this form takes much less time than the repeat with x = firstValue to lastValue form:

repeat for each character tChar in pString
	put tChar before tReversed
end repeat

However, this turns out to be slower in this particular case. The reason is that it takes longer to put a string before a variable than to put a string after a variable. Since we need to reverse the string, and since the repeat for each form doesn't have a way to go backwards, we have no choice but to put each character before the tReversedString variable. The speed loss from doing this is much greater for this handler than the speed we'd gain from using the repeat for each form.

Keywords used in this example

0 Comments

Add your comment

E-Mail me when someone replies to this comment