Logo

Programming-Idioms

  • PHP
  • C++
  • Python
  • JS

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"
String t = "";
for (char c : s.toCharArray())
    t = c + t;
char a[] = s.toCharArray(), c;
int i, m = a.length, n = m-- / 2, z;
for (i = 0; i < n; ++i) {
    c = a[i];
    a[i] = a[z = m - i];
    a[z] = c;
}
String t = new String(a);
String t = new StringBuilder(s).reverse().toString();

StringBuilder is available since Java 1.5
import static java.lang.String.valueOf;
import static java.lang.System.out;
String t = s.chars()
    .mapToObj(x -> valueOf((char) x))
    .reduce((a, b) -> b + a)
    .get();
for ($i=0;$i<mb_strlen($s);$i++) {
    $characters[] = mb_substr($s, $i, 1, 'UTF-8');
}

$characters = array_reverse($characters);
$t = implode($characters);

This solution needs mb (multibyte) extension.
#include <algorithm>
#include <string>
auto t = ::std::ranges::reverse(s);
t = s[::-1]
t = ''.join(reversed(s))
var t = s.split("").reverse().join("");
#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