Logo

Programming-Idioms

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

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"
my $s = 'cafe' . "\N{COMBINING ACUTE ACCENT}";
my $t = join '', reverse $s =~ /\X/g;

Bet your programming language is not Unicode compliant. Perl, in general, is. Sad state of affairs: https://www.azabani.com/pages/gbu/

As of 2019-09-29, all other solutions are wrong AFAICT with respect to Unicode marks. (Dart has a disclaimer.)

Correct result: "e\N{U+0301}fac"
Wrong result: "\N{U+0301}efac"
#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