Logo

Programming-Idioms

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

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 ReverseString(const AText: string): string;
var
    i,j:longint;
begin
  setlength(result,length(atext));
  i:=1; j:=length(atext);
  while (i<=j) do
    begin
      result[i]:=atext[j-i+1];
      inc(i);
    end;
end;
function reverse(const str: string): string;
var
  i, j: Integer;
begin
  j := length(str);
  setlength(reverse, j);
  for i := 1 to j do
    reverse[i] := str[j - i + 1];
end;
#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