Logo

Programming-Idioms

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

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"
#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;
}
(let [s "hello"
      t (apply str (reverse s))]
  t)
(require '[clojure.string :as str])
(def t (str/reverse s))
IDENTIFICATION DIVISION.
PROGRAM-ID. reverse string.
PROCEDURE DIVISION.
    MOVE FUNCTION REVERSE(s) TO t
STOP RUN.
char[] charArray = s.ToCharArray();
Array.Reverse(charArray);
string t = new string(charArray);
string t = string.Create(s.Length, s, static (span, s) =>
{
    s.AsSpan().CopyTo(span);
    span.Reverse();
});
import std.range, std.array;
auto t = s.retro.array;
var t = new String.fromCharCodes(s.runes.toList().reversed);
var t = s.split('').reversed.join();

t = String.reverse(s)
T = lists:reverse(S)
  character(len=:), allocatable :: t
  integer :: i, n

  allocate (t, mold=s)
  n = len(s)
  do i = 0, n - 1
     t(n-i : n-i) = s(i+1 : i+1)
  end do
import "slices"
runes := []rune(s)
slices.Reverse(runes)
t := string(runes)
import (
  "strings"
  "unicode/utf8"
)
func reverse(s string) string {
	if len(s) <= 1 {
		return s
	}
	var b strings.Builder
	b.Grow(len(s))
	for len(s) > 0 {
		r, l := utf8.DecodeLastRuneInString(s)
		s = s[:len(s)-l]
		b.WriteRune(r)
	}
	return b.String()
}
runes := []rune(s)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
   runes[i], runes[j] = runes[j], runes[i]
}
t := string(runes)
t = reverse s :: String
var t = s.split("").reverse().join("");
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();
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();
val t = s.reversed()
(reverse s)
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)
@import Foundation;
NSMutableString *t=[NSMutableString string];
[s enumerateSubstringsInRange:NSMakeRange(0,s.length)
  options:NSStringEnumerationReverse|NSStringEnumerationByComposedCharacterSequences
  usingBlock:^(NSString *part, NSRange r1, NSRange r2, BOOL *stop) {
    [t appendString:part];
}];
for ($i=0;$i<mb_strlen($s);$i++) {
    $characters[] = mb_substr($s, $i, 1, 'UTF-8');
}

$characters = array_reverse($characters);
$t = implode($characters);
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;
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;
my $s = 'cafe' . "\N{COMBINING ACUTE ACCENT}";
my $t = join '', reverse $s =~ /\X/g;
t = s[::-1]
t = ''.join(reversed(s))
t = s.reverse
let t: String = s.chars().rev().collect();
let t = s.chars().rev().collect::<String>();
s.reverse
(define t (list->string (reverse (string->list s))))
t := s reversed.
Dim string_t = StrReverse(string_s)

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