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

Idiom #41 Reverse a string

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

Illustration
var t = new String.fromCharCodes(s.runes.toList().reversed);
char[] charArray = s.ToCharArray();
Array.Reverse(charArray);
string t = new string(charArray);
import std.range, std.array;
auto t = "The key to learning D is to 脚踏实地".retro.array;
t = String.reverse(s)
T = lists:reverse(S)
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
-1
s = t.split("").reverse().join("");
String t = new StringBuilder(s).reverse().toString();
function utf8.reverse(s)
	local r = ""
	for p,c in utf8.codes(s) do
		r = utf8.char(c)..r
	end
	return r
end

r = utf8.reverse(s)
$s = "lorém ipsüm dolör sit amor ❤ ";

for ($i=0;$i<mb_strlen($s);$i++) {

    $characters[] = mb_substr($s, $i, 1, 'UTF-8');

}

$characters = array_reverse($characters);
$t = implode($characters);
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;
$reversed = reverse "reversing a string is simple";
t = s[::-1]
t = s.reverse
let s = "lorém ipsüm dolör sit amor ❤ ";
let t = s.chars().rev().collect::<String>();
"SomeString".reverse

Do you know the best way to do this in your language ?
New implementation...

Idiom created by

programming-idioms.org

Related idioms