Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Lua

Idiom #41 Reverse a string

Create the string t containing the same characters as the string s, in reverse order.
The original string s must remain unaltered. Each character must be handled correctly regardless its number of bytes in memory.

Turning the string "café" into "éfac"
function utf8.reverse(s)
	local r = ""
	for p,c in utf8.codes(s) do
		r = utf8.char(c)..r
	end
	return r
end

t = utf8.reverse(s)

if string s is an ascii string you can directly use string.reverse instead.

You will also need Lua5.3 or an utf8 module
#include <stdlib.h>
#include <string.h>
char *strrev(char *s)
{
	size_t len = strlen(s);
	char *rev = malloc(len + 1);

	if (rev) {
		char *p_s = s + len - 1;
		char *p_r = rev;

		for (; len > 0; len--)
			*p_r++ = *p_s--;
		*p_r = '\0';
	}
	return rev;
}

Returns NULL on failure

New implementation...
< >
programming-idioms.org