Reverse a string

From Rosetta Code
Jump to: navigation, search
Task
Reverse a string
You are encouraged to solve this task according to the task description, using any language you may know.
Take a string and reverse it. For example, "asdf" becomes "fdsa".

For extra credit, preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa".

Contents

[edit] 0815

This program reverses each line of its input.

}:r:     Start reader loop.
 !~>& Push a character to the "stack".
<:a:=- Stop reading on newline.
^:r:
@> Rotate the newline to the end and enqueue a sentinel 0.
{~ Dequeue and rotate the first character into place.
}:p:
${~ Print the current character until it's 0.
^:p:
#:r: Read again.
Output:
echo -e "foo\nbar" | 0815 rev.0
oof
rab

[edit] ACL2

(reverse "hello")

ACL2 does not support unicode.

[edit] ActionScript

function reverseString(string:String):String
{
var reversed:String = new String();
for(var i:int = string.length -1; i >= 0; i--)
reversed += string.charAt(i);
return reversed;
}
 
function reverseStringCQAlternative(string:String):String
{
return string.split('').reverse().join('');
}

[edit] Ada

with Ada.Text_IO; use Ada.Text_IO;
 
procedure Reverse_String is
function Reverse_It (Item : String) return String is
Result : String (Item'Range);
begin
for I in Item'range loop
Result (Result'Last - I + Item'First) := Item (I);
end loop;
return Result;
end Reverse_It;
begin
Put_Line (Reverse_It (Get_Line));
end Reverse_String;

[edit] Agda2

Using the Agda standard library, version 0.6.

module reverse_string where
 
open import Data.String
open import Data.List
 
reverse_string : String → String
reverse_string s = fromList (reverse (toList s))

[edit] Aime

text
reverse(text s)
{
data b;
integer i;
 
i = length(s);
while (i) {
i -= 1;
b_insert(b, -1, character(s, i));
}
 
return b_string(b);
}
 
integer
main(void)
{
o_text(reverse("Hello, World!"));
o_byte('\n');
 
return 0;
}

[edit] ALGOL 68

Works with: ALGOL 68 version Standard - no extensions to language used
Works with: ALGOL 68G version Any - tested with release mk15-0.8b.fc9.i386
Works with: ELLA ALGOL 68 version Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386
PROC reverse = (REF STRING s)VOID:
FOR i TO UPB s OVER 2 DO
CHAR c = s[i];
s[i] := s[UPB s - i + 1];
s[UPB s - i + 1] := c
OD;
 
main:
(
STRING text := "Was it a cat I saw";
reverse(text);
print((text, new line))
)
Output:
was I tac a ti saW

[edit] APL

      ⌽'asdf'
fdsa

[edit] AppleScript

get reverse_string("as⃝df̅")
 
on reverse_string(str)
set old_delim to (get AppleScript's text item delimiters)
set AppleScript's text item delimiters to ""
 
set temp to (reverse of text items of str)
set temp to (text items of temp) as Unicode text
 
set AppleScript's text item delimiters to old_delim
return temp
end reverse_string

[edit] AutoHotkey

"Normal" version:
MsgBox % reverse("asdf")
 
reverse(string)
{
Loop, Parse, string
reversed := A_LoopField . reversed
Return reversed
}
A ''much'' faster version:
Reverse(String){ ; credit to Rseding91
If (A_IsUnicode){
SLen := StrLen(String) * 2
VarSetCapacity(RString,SLen)
 
Loop,Parse,String
NumPut(Asc(A_LoopField),RString,SLen-(A_Index * 2),"UShort")
} Else {
SLen := StrLen(String)
VarSetCapacity(RString,SLen)
 
Loop,Parse,String
NumPut(Asc(A_LoopField),RString,SLen-A_Index,"UChar")
}
 
VarSetCapacity(RString,-1)
 
Return RString
}

[edit] Applesoft BASIC

10 A$ = "THE FIVE BOXING WIZARDS JUMP QUICKLY"
20 GOSUB 100REVERSE
30 PRINT R$
40 END
 
100 REMREVERSE A$
110 R$ = ""
120 FOR I = 1 TO LEN(A$)
130 R$ = MID$(A$, I, 1) + R$
140 NEXT I
150 RETURN

[edit] AutoIt

#AutoIt Version: 3.2.10.0
$mystring="asdf"
$reverse_string = ""
$string_length = StringLen($mystring)
 
For $i = 1 to $string_length
$last_n_chrs = StringRight($mystring, $i)
$nth_chr = StringTrimRight($last_n_chrs, $i-1)
$reverse_string= $reverse_string & $nth_chr
Next
 
MsgBox(0, "Reversed string is:", $reverse_string)

[edit] AWK

function reverse(s)
{
p = ""
for(i=length(s); i > 0; i--) { p = p substr(s, i, 1) }
return p
}
 
BEGIN {
print reverse("edoCattesoR")
}
Recursive
function reverse(s   ,l)
{
l = length(s)
return l < 2 ? s:( substr(s,l,1) reverse(substr(s,1,l-1)) )
}
 
BEGIN {
print reverse("edoCattesoR")
}

[edit] Babel

This example will handle UTF-8 encoded Unicode but doesn't handle combining characters.

strrev: { str2ar ar2ls reverse ls2lf ar2str }
  • str2ar - this operator converts a UTF-8 encoded string to an array of Unicode codepoints
  • ar2ls - this operator converts the array to a linked-list
  • reverse - this operator reverses a linked-list
  • ls2lf - this operator undoes the effect of ar2ls
  • ar2str - this operator undoes the effect of str2ar

[edit] BASIC

Works with: QuickBasic version 4.5
FUNCTION reverse$(a$)
b$ = ""
FOR i = 1 TO LEN(a$)
b$ = MID$(a$, i, 1) + b$
NEXT i
reverse$ = b$
END FUNCTION

[edit] Batch File

@echo off
setlocal enabledelayedexpansion
call :reverse %1 res
echo %res%
goto :eof
 
:reverse
set str=%~1
set cnt=0
:loop
if "%str%" equ "" (
goto :eof
)
set chr=!str:~0,1!
set str=%str:~1%
set %2=%chr%!%2!
goto loop

[edit] BBC BASIC

      PRINT FNreverse("The five boxing wizards jump quickly")
END
 
DEF FNreverse(A$)
LOCAL B$, C%
FOR C% = LEN(A$) TO 1 STEP -1
B$ += MID$(A$,C%,1)
NEXT
= B$

[edit] Befunge

To see this in action, it's best to use an interpreter that animates the process.

v  The string to reverse. The row to copy to.
| | The actual copying happens here.
| | | Increment column to write to.
| | | | Store column #.
v v v v v
> "reverse me" 3 10p >10g 4 p 10g1+ 10pv
^ ^ |: <
First column --| | @ ^
to write to. | ^ Get the address
All calls to 10 | to copy the next
involve saving or | character to.
reading the End when stack is empty or
column to write explicit zero is reached.
to.

[edit] Bracmat

  ( reverse
= L x
.  :?L
& @( !arg
 :  ?
( %?x
& utf$!x
& !x !L:?L
& ~`
)
 ?
)
| str$!L
)
& out$reverse$Ελληνικά
Output:
άκινηλλΕ

[edit] Brainf***

[-]>,+[->,+]<[.<]

The former wont stop taking input bytes unless a special compiler was made to stop at ENTER. The following checks for 10 ascii (line feed) and stops taking input at that point

,----- ----- [+++++ +++++ > , ----- -----]	If a newline is hit counter will be zero and input loop ends
<[.<] run all chars backwards and print them
 
just because it looks good we print CRLF
+++++ +++++ +++ . --- .

[edit] Brat

p "olleh".reverse  #Prints "hello"

[edit] Burlesque

 
"Hello, world!"<-
 

[edit] C

#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <wchar.h>
 
const char *sa = "abcdef";
const char *su = "as⃝df̅"; /* Should be in your native locale encoding. Mine is UTF-8 */
 
int is_comb(wchar_t c)
{
if (c >= 0x300 && c <= 0x36f) return 1;
if (c >= 0x1dc0 && c <= 0x1dff) return 1;
if (c >= 0x20d0 && c <= 0x20ff) return 1;
if (c >= 0xfe20 && c <= 0xfe2f) return 1;
return 0;
}
 
wchar_t* mb_to_wchar(const char *s)
{
wchar_t *u;
size_t len = mbstowcs(0, s, 0) + 1;
if (!len) return 0;
 
u = malloc(sizeof(wchar_t) * len);
mbstowcs(u, s, len);
return u;
}
 
wchar_t* ws_reverse(const wchar_t* u)
{
size_t len, i, j;
wchar_t *out;
for (len = 0; u[len]; len++);
out = malloc(sizeof(wchar_t) * (len + 1));
out[len] = 0;
j = 0;
while (len) {
for (i = len - 1; i && is_comb(u[i]); i--);
wcsncpy(out + j, u + i, len - i);
j += len - i;
len = i;
}
return out;
}
 
char *mb_reverse(const char *in)
{
size_t len;
char *out;
wchar_t *u = mb_to_wchar(in);
wchar_t *r = ws_reverse(u);
len = wcstombs(0, r, 0) + 1;
out = malloc(len);
wcstombs(out, r, len);
free(u);
free(r);
return out;
}
 
int main(void)
{
setlocale(LC_CTYPE, "");
 
printf("%s => %s\n", sa, mb_reverse(sa));
printf("%s => %s\n", su, mb_reverse(su));
return 0;
}
Output:
abcdef => fedcba
as⃝df̅ => f̅ds⃝a
Library: GLib
#include <glib.h>
gchar *srev (const gchar *s) {
if (g_utf8_validate(s,-1,NULL)) {
return g_utf8_strreverse (s,-1);
} }
// main
int main (void) {
const gchar *t="asdf";
const gchar *u="as⃝df̅";
printf ("%s\n",srev(t));
printf ("%s\n",srev(u));
return 0;
}

[edit] C++

#include <iostream>
#include <string>
#include <algorithm>
 
int main()
{
std::string s;
std::getline(std::cin, s);
std::reverse(s.begin(), s.end()); // modifies s
std::cout << s << std::endl;
return 0;
}

[edit] C#

C# does not have a built-in Reverse method for strings, which are immutable. One way to implement this is to convert the string to an array of characters, reverse that, and return a new string from the reversed array:

private static string ReverseString(string input)
{
char[] inputChars = input.ToCharArray();
Array.Reverse(inputChars);
return new string(inputChars);
}

As of .Net 3.5 you can call LINQ's Reverse extension method on a string, since String implements the IEnumerable<char> interface. Because of this, the return type of Reverse is IEnumerable<char>. Fortunately, LINQ also provides the ToArray extension method, which can be used in conjunction with one of the constructors belonging to the String class which accepts an array of chars:

return new string(input.Reverse().ToArray());

[edit] Caché ObjectScript

USER>Write $Reverse("Hello, World")
dlroW ,olleH

[edit] Clipper

Works with versions since 5, because LOCAL variables and the += operator was not implemented before.

FUNCTION Reverse(sIn)
LOCAL sOut := "", i
FOR i := Len(sIn) TO 1 STEP -1
sOut += Substr(sIn, i, 1)
NEXT
RETURN sOut

[edit] Clojure

[edit] Basic reverse

For normal strings, the reverse function can be used to do the bulk of the work. However, it returns a character sequence, which has to be converted back to a string.

(defn str-reverse [s] (apply str (reverse s)))

[edit] Reverse words in a string

(apply str (interpose " " (reverse (.split "the quick brown fox" " "))))

[edit] Supporting combining characters

Handling combining characters present a trickier task. We need to protect the relative ordering of the combining character and the character to its left. Thus, before reversing, the characters need to be grouped.

(defn combining? [c]
(let [type (Character/getType c)]
;; currently hardcoded to the types taken from the sample string
(or (= type 6) (= type 7))))
 
(defn group
"Group normal characters with their combining characters"
[chars]
(cond (empty? chars) chars
(empty? (next chars)) (list chars)
:else
(let [dres (group (next chars))]
(cond (combining? (second chars)) (cons (cons (first chars)
(first dres))
(rest dres))
:else (cons (list (first chars)) dres)))))
 
(defn str-reverse
"Unicode-safe string reverse"
[s]
(apply str (apply concat (reverse (group s)))))
Output:
user=> s
"as⃝df̅"
user=> (str-reverse s)
"f̅ds⃝a"[
user=> (str-reverse (str-reverse s))
"as⃝df̅"
user=>

[edit] COBOL

FUNCTION REVERSE('QWERTY')

[edit] CoffeeScript

"qwerty".split("").reverse().join ""

[edit] ColdFusion

You can reverse anything that can be written to the document in hashmarks (i.e. strings, numbers, now( ), etc.).

<cfset myString  = "asdf" />
<cfset myString = reverse( myString ) />

[edit] Common Lisp

(reverse my-string)

[edit] Component Pascal

BlackBox Component Builder

 
MODULE BbtReverseString;
IMPORT StdLog;
 
PROCEDURE ReverseStr(str: ARRAY OF CHAR): POINTER TO ARRAY OF CHAR;
VAR
top,middle,i: INTEGER;
c: CHAR;
rStr: POINTER TO ARRAY OF CHAR;
BEGIN
NEW(rStr,LEN(str$) + 1);
top := LEN(str$) - 1; middle := (top - 1) DIV 2;
FOR i := 0 TO middle DO
rStr[i] := str[top - i];
rStr[top - i] := str[i];
END;
IF ODD(LEN(str$)) THEN rStr[middle + 1] := str[middle + 1] END;
RETURN rStr;
END ReverseStr;
 
PROCEDURE Do*;
VAR
x: CHAR;
BEGIN
StdLog.String("'asdf' reversed:> ");StdLog.String(ReverseStr("asdf"));StdLog.Ln
END Do;
END BbtReverseString.
 

Execute: ^Q BbtReverseString.Do
Output:

'asdf' reversed:> fdsa

[edit] D

void main() {
import std.range, std.conv;
 
string s1 = "hello"; // UTF-8
assert(s1.retro.text == "olleh");
 
wstring s2 = "hello"w; // UTF-16
assert(s2.retro.wtext == "olleh"w);
 
dstring s3 = "hello"d; // UTF-32
assert(s3.retro.dtext == "olleh"d);
 
// without using std.range:
dstring s4 = "hello"d;
assert(s4.dup.reverse == "olleh"d); // simple but inefficient (copies first, then reverses)
}

[edit] Dart

Since Dart strings are sequences of UTF-16 code units, it would not be sufficient to simply reverse the characters in strings, as this would not work with UTF-16 surrogate pairs (pairs of UTF-16 code units that represent single characters outside the Unicode BMP). However, Dart provides a method to convert strings to sequences of unicode code points (called "runes" in Dart), and these sequences can easily be reversed and used to create new strings, so a string reversal function can be written with a single line of Dart code:

String reverse(String s) => new String.fromCharCodes(s.runes.toList().reversed);

A more complete example with unit tests would look like this:

import 'package:unittest/unittest.dart';
 
String reverse(String s) => new String.fromCharCodes(s.runes.toList().reversed);
 
main() {
group("Reverse a string -", () {
test("Strings with ASCII characters are reversed correctly.", () {
expect(reverse("hello, world"), equals("dlrow ,olleh"));
});
test("Strings with non-ASCII BMP characters are reversed correctly.", () {
expect(reverse("\u4F60\u4EEC\u597D"), equals("\u597D\u4EEC\u4F60"));
});
test("Strings with non-BMP characters are reversed correctly.", () {
expect(reverse("hello, \u{1F310}"), equals("\u{1F310} ,olleh"));
});
});
}

[edit] Delphi

function ReverseString(const InString: string): string;
var
i: integer;
begin
for i := Length(InString) downto 1 do
Result := Result + InString[i];
end;

You could also use this RTL function Introduced in Delphi 6:

StrUtils.ReverseString

[edit] Déjà Vu

!print concat chars "Hello"
Output:
olleH

[edit] DWScript

See Delphi.

[edit] E

pragma.enable("accumulator")
def reverse(string) {
return accum "" for i in (0..!(string.size())).descending() { _ + string[i] }
}

[edit] Emacs Lisp

(concat (reverse (append "Hello World" nil)))
Output:
"dlroW olleH"

[edit] Eiffel

class
APPLICATION
create
make
feature
make
-- Demonstrate string reversal.
do
my_string := "Hello World!"
my_string.mirror
print (my_string)
end
my_string: STRING
-- Used for reversal
end
Output:
!dlroW olleH

[edit] EGL

function reverse( str string ) returns( string )
result string;
for ( i int from StrLib.characterLen( str ) to 1 decrement by 1 )
result ::= str[i:i];
end
return( result );
end

[edit] Elixir

Elixir handles Unicode graphemes correctly by default.

 
IO.puts (String.reverse "asdf")
IO.puts (String.reverse "as⃝df̅")
 

Output:

fdsa
f̅ds⃝a

[edit] Erlang

1> lists:reverse("reverse!").
"!esrever"

Erlang also supports binary strings, which uses its binary format. There is no standard function to reverse a binary sequence, but the following one does the job well enough. It works by changing the endianness (from little to big or the opposite) of the whole sequence, effectively reversing the string.

reverse(Bin) ->
Size = size(Bin)*8,
<<T:Size/integer-little>> = Bin,
<<T:Size/integer-big>>.
Output:
1> test:reverse(<<"hello">>).
<<"olleh">>

[edit] Euler Math Toolbox

 
>function strrev (s) := chartostr(fliplr(strtochar(s)))
>strrev("This is a test!")
 !tset a si sihT
 

[edit] Euphoria

 
include std/sequence.e
printf(1, "%s\n", {reverse("abcdef") })
 

[edit] Ezhil

 
 
## இந்த நிரல் தரப்படும் சரம் ஒன்றைத் தலைகீழாகத் திருப்பி அச்சிடும்
## உதாரணமாக "abc" என்ற சரம் தரப்பட்டால் அதனைத் திருப்பி "cba" என அச்சிடும்
## "எழில்" மொழியின்மூலம் இரண்டு வகைகளில் இதனைச் செய்யலாம். இரண்டு உதாரணங்களும் இங்கே தரப்பட்டுள்ளன
 
நிரல்பாகம் திருப்புக (சரம்1)
 
## முதல் வகை
 
சரம்2 = ""
 
@( சரம்1 இல் இ) ஒவ்வொன்றாக
சரம்2 = இ + சரம்2
முடி
 
பின்கொடு சரம்2
 
முடி
 
நிரல்பாகம் மீண்டும்திருப்புக (சரம்1)
 
## இரண்டாம் வகை
 
சரநீளம் = len(சரம்1)
 
சரம்2 = ""
 
@(எண் = 0, எண் < சரநீளம், எண் = எண் + 1) ஆக
 
சரம்2 = எடு(சரம்1, எண்) + சரம்2
 
முடி
 
பின்கொடு சரம்2
 
முடி
 
 
அ = உள்ளீடு("ஓர் எழுத்துச் சரத்தைத் தாருங்கள் ")
 
பதிப்பி "நீங்கள் தந்த எழுத்துச் சரம்" அ
 
பதிப்பி "அதனை முதல் வகையில் திருப்பியுள்ளோம்: " திருப்புக(அ)
 
பதிப்பி "வேறொரு வகையில் திருப்பியுள்ளோம்: " மீண்டும்திருப்புக(அ)
 
 

[edit] FBSL

A slow way

FUNCTION StrRev1(BYVAL $p1)
DIM $b = ""
REPEAT LEN(p1)
b = b & RIGHT(p1,1)
p1 = LEFT(p1,LEN(p1)-1)
END REPEAT
RETURN b
END FUNCTION
 

A much faster (twice at least) way

FUNCTION StrRev2(BYVAL $p1)
DIM $b = "", %i
FOR i = LEN(p1) DOWNTO 1
b = b & MID(p1,i,1)
NEXT
RETURN b
END FUNCTION

An even faster way using PEEK, POKE, double-calls and quantity-in-hand

FUNCTION StrRev3( $s )
FOR DIM x = 1 TO LEN(s) \ 2
PEEK(@s + LEN - x, $1)
POKE(@s + LEN - x, s{x})(@s + x - 1, PEEK)
NEXT
RETURN s
END FUNCTION
 

An even faster way using the DynC (Dynamic C) mode

DynC StringRev($theString) As String
void rev(char *str)
{
int len = strlen(str);
char *HEAD = str;
char *TAIL = str + len - 1;
char temp;
int i;
for ( i = 0; i <= len / 2; i++, HEAD++, TAIL--) {
temp = *HEAD;
*HEAD = *TAIL;
*TAIL = temp;
}
}
char *main(char* theString)
{
rev(theString);
return theString;
}
End DynC

Using DynASM, the Dynamic Assembler mode.

DYNASM RevStr(BYVAL s AS STRING) AS STRING
// get length of string
// divide by two
// setup pointers to head and tail
// iterate from 1 to (length \ 2)
// swap head with tail
// increment head pointer
// decrement tail pointer
 
ENTER 0, 0 // = PUSH EBP: MOV EBP, ESP
PUSH EBX // by Windows convention EBX, EDI, ESI must be saved before modification
 
MOV EAX, s // get string pointer
MOV ECX, EAX // duplicate it
 
.WHILE BYTE PTR [ECX] <> 0
 
INC ECX // propagate to tail
 
.WEND
 
MOV EDX, ECX // duplicate tail pointer
DEC EDX // set it to last byte before trailing zero
 
SUB ECX, EAX // get length in ECX in 1 CPU cycle
SHR ECX, 1 // get length \ 2 in 1 CPU cycle; that's the beauty of power-of-two division
 
.WHILE ECX > 0
 
MOV BL, [EDX] // no need to XOR; just overwrite BL and BH contents
MOV BH, [EAX] // DynAsm deduces data size from destination register sizes
 
MOV [EDX], BH // ditto, source register sizes
MOV [EAX], BL
 
INC EAX // propagate pointers
DEC EDX
 
DEC ECX // decrement counter
 
.WEND
 
// point to start of string again
MOV EAX, s // MOV = 1 CPU cycle, PUSH + POP = 2 CPU cycles
 
POP EBX // by Windows convention ESI, EDI, EBX must be restored if modified
LEAVE // = POP EBP
RET
END DYNASM
 

[edit] F#

let ReverseString (s:string) = new string(Array.rev (s.ToCharArray()))

[edit] Factor

A string is a sequence and there is a default reverse implementation for those.

"hello" reverse

string-reverse preserves graphemes:

"as⃝df̅" string-reverse "f̅ds⃝a" = .

[edit] FALSE

This solution does not take into account combination characters:

1_
[^$1_=~][]#%
[$1_=~][,]#

This solution does take into account combination characters (except for half-marks):

1_
[^$1_=~][
$$767>\879\>&
1ø$7615>\7620\>&|
1ø$8399>\8428\>&|
[\]?
]#%
[$1_=~][,]#

[edit] Fancy

"hello world!" reverse

[edit] Forth

: exchange ( a1 a2 -- )
2dup c@ swap c@ rot c! swap c! ;
: reverse ( c-addr u -- )
1- bounds begin 2dup > while
2dup exchange
-1 /string
repeat 2drop ;
 
s" testing" 2dup reverse type \ gnitset

[edit] Fortran

Works with: Fortran version 90 and later
PROGRAM Example
 
CHARACTER(80) :: str = "This is a string"
CHARACTER :: temp
INTEGER :: i, length
 
WRITE (*,*) str
length = LEN_TRIM(str) ! Ignores trailing blanks. Use LEN(str) to reverse those as well
DO i = 1, length/2
temp = str(i:i)
str(i:i) = str(length+1-i:length+1-i)
str(length+1-i:length+1-i) = temp
END DO
WRITE(*,*) str
 
END PROGRAM Example
Output:
This is a string
gnirts a si sihT

Another implementation that uses a recursive not-in-place algorithm:

program reverse_string
 
implicit none
character (*), parameter :: string = 'no devil lived on'
 
write (*, '(a)') string
write (*, '(a)') reverse (string)
 
contains
 
recursive function reverse (string) result (res)
 
implicit none
character (*), intent (in) :: string
character (len (string)) :: res
 
if (len (string) == 0) then
res = ''
else
res = string (len (string) :) // reverse (string (: len (string) - 1))
end if
 
end function reverse
 
end program reverse_string
Output:
no devil lived on
no devil lived on

[edit] Frink

The built-in reverse function reverses a string or the elements of a list.

println[reverse["abcdef"]]

[edit] GAP

Reversed("abcdef");
# "fedcba"

[edit] Gema

Reverse each line in the input stream. Using built in function:

\L<U>=@reverse{$1}

Not using built in function (recursively apply substring to same rule):

\L<U1><U>=@{$2}$1

[edit] Go

Functions below assume UTF-8 encoding. (The task mentions Unicode but does not specify an encoding.) Strings in Go are not restricted to be UTF-8, but Go has good support for it and works with UTF-8 most natually. As shown below, certain string conversions work in UTF-8 and the range clause over a string works in UTF-8. Go also has a Unicode package in the standard library that makes easy work of recognizing combining characters for this task.

package main
 
import (
"fmt"
"unicode"
"unicode/utf8"
)
 
// no encoding
func reverseBytes(s string) string {
r := make([]byte, len(s))
for i := 0; i < len(s); i++ {
r[i] = s[len(s)-1-i]
}
return string(r)
}
 
// reverseCodePoints interprets its argument as UTF-8 and ignores bytes
// that do not form valid UTF-8. return value is UTF-8.
func reverseCodePoints(s string) string {
r := make([]rune, len(s))
start := len(s)
for _, c := range s {
// quietly skip invalid UTF-8
if c != utf8.RuneError {
start--
r[start] = c
}
}
return string(r[start:])
}
 
// reversePreservingCombiningCharacters interprets its argument as UTF-8
// and ignores bytes that do not form valid UTF-8. return value is UTF-8.
func reversePreservingCombiningCharacters(s string) string {
if s == "" {
return ""
}
p := []rune(s)
r := make([]rune, len(p))
start := len(r)
for i := 0; i < len(p); {
// quietly skip invalid UTF-8
if p[i] == utf8.RuneError {
i++
continue
}
j := i + 1
for j < len(p) && (unicode.Is(unicode.Mn, p[j]) ||
unicode.Is(unicode.Me, p[j]) || unicode.Is(unicode.Mc, p[j])) {
j++
}
for k := j - 1; k >= i; k-- {
start--
r[start] = p[k]
}
i = j
}
return (string(r[start:]))
}
 
func main() {
test("asdf")
test("as⃝df̅")
}
 
func test(s string) {
fmt.Println("\noriginal: ", []byte(s), s)
r := reverseBytes(s)
fmt.Println("reversed bytes:", []byte(r), r)
fmt.Println("original code points:", []rune(s), s)
r = reverseCodePoints(s)
fmt.Println("reversed code points:", []rune(r), r)
r = reversePreservingCombiningCharacters(s)
fmt.Println("combining characters:", []rune(r), r)
}
Output:
original:       [97 115 100 102] asdf
reversed bytes: [102 100 115 97] fdsa
original code points: [97 115 100 102] asdf
reversed code points: [102 100 115 97] fdsa
combining characters: [102 100 115 97] fdsa

original:       [97 115 226 131 157 100 102 204 133] as⃝df̅
reversed bytes: [133 204 102 100 157 131 226 115 97] ��fd���sa
original code points: [97 115 8413 100 102 773] as⃝df̅
reversed code points: [773 102 100 8413 115 97] ̅fd⃝sa
combining characters: [102 773 100 115 8413 97] f̅ds⃝a

[edit] Groovy

Solution:

println "Able was I, 'ere I saw Elba.".reverse()
Output:
.ablE was I ere' ,I saw elbA


[edit] Harbour

FUNCTION Reverse( sIn )
 
LOCAL cOut := "", i
 
FOR i := Len( sIn ) TO 1 STEP -1
cOut += Substr( sIn, i, 1 )
NEXT
 
RETURN cOut

[edit] Haskell

reverse = foldl (flip (:)) []

This function as defined in the Haskell Prelude.

[edit] Supporting combining characters

import Data.Char (isMark)
import Data.List (groupBy)
myReverse = concat . reverse . groupBy (const isMark)

groupBy (const isMark) is an unusual way of splitting a string into its combined characters

[edit] HicEst

CHARACTER string = "Hello World", tmp
 
L = LEN( string )
DO i = 1, L/2
tmp = string(i)
string(i) = string(L-i+1)
string(L-i+1) = tmp
ENDDO
 
WRITE(Messagebox, Name) string

[edit] Icon and Unicon

procedure main(arglist)
s := \arglist[1] | "asdf"
write(s," <-> ", reverse(s)) # reverse is built-in
end

[edit] Io

"asdf" reverse

[edit] J

Reverse (|.) reverses a list of items (of any shape or type).

   |.'asdf'
fdsa

Extra credit: First, a function to determine whether a Unicode character is a combining character:

   ranges=.16b02ff 16b036f, 16b1dbf 16b1dff, 16b20cf 16b20ff, 16bfe1f 16bfe2f
iscombining=. 2 | ranges&I.

Then we need to box groups of letters and combining characters, reverse, and unbox. The boxing function can be carried out easily with dyad cut, which uses the indices of the ones on the right as the starting points for groups of characters. For clarity, its inverse will be defined as raze, which simply runs together the items inside boxes of its argument.

   split=. (<;.1~ -.@iscombining) :. ;

After this, the solution is just to reverse under the split transformation. This also takes place under J code to convert from Unicode to integers.

   |.&.split&.(3 u: 7&u:) 'as⃝df̅'
f̅ds⃝a

[edit] Java

public static String reverseString(String s) {
return new StringBuffer(s).reverse().toString();
}
Works with: Java version 1.5+
public static String reverseString(String s) {
return new StringBuilder(s).reverse().toString();
}

[edit] JavaScript

var a = "cat".split("");
a.reverse();
print(a.join("")); // tac

[edit] Julia

julia> reverse("hey")
"yeh"

[edit] L++

(include "string" "algorithm")
(main
(decl std::string s)
(std::getline std::cin s)
(std::reverse (s.begin) (s.end))
(prn s))

[edit] LabVIEW

This image is a VI Snippet, an executable image of LabVIEW code. The LabVIEW version is shown on the top-right hand corner. You can download it, then drag-and-drop it onto the LabVIEW block diagram from a file browser, and it will appear as runnable, editable code.
LabVIEW Reverse a string.png

[edit] Lang5

: flip "" split reverse "" join ;
"qwer asdf" flip .

[edit] Lasso

local(input) = 'asdf'
#input->reverse

[edit] Using Query Expression & Array

More verbose than the string->reverse method, but this example illustrates different techniques to achieve the same result: using string->values to iterate over a string in order, inserting at position 1, and joining the resulting array as a string.

local(input = 'asdf', output = array)
with i in #input->values
do #output->insertFirst(#i)
#output->join

[edit] Liberty BASIC

input$ ="abcdefgABCDEFG012345"
print input$
print ReversedStr$( input$)
 
end
 
function ReversedStr$(in$)
for i =len(in$) to 1 step -1
ReversedStr$ =ReversedStr$ +mid$( in$, i, 1)
next i
end function

[edit] LiveCode

function reverseString S
repeat with i = length(S) down to 1
put char i of S after R
end repeat
return R
end reverseString

[edit]

REVERSE works on both words and lists.

print reverse "cat   ; tac

[edit] Lua

Built-in string.reverse(s) or s:reverse().

theString = theString:reverse()

[edit] M4

define(`invert',`ifelse(len(`$1'),0,,`invert(substr(`$1',1))'`'substr(`$1',0,1))')

[edit] Maple

> StringTools:-Reverse( "foo" );
"oof"

[edit] Mathematica

StringReverse["asdf"]

[edit] MATLAB

A built-in function, "fliplr(string)" handles reversing a string of ASCII characters. Unicode is a whole other beast, if you need this functionality test to see if "fliplr()" properly handles the unicode characters you use. If it doesn't then you will need to code a function that is specific to your application.

Sample Usage:

>> fliplr(['She told me that she spoke English and I said great. '...
'Grabbed her hand out the club and I said let''s skate.'])
 
ans =
 
.etaks s'tel dias I dna bulc eht tuo dnah reh debbarG .taerg dias I dna hsilgnE ekops ehs taht em dlot ehS

[edit] Maxima

sreverse("abcdef");         /* "fedcba" */
 
sreverse("rats live on no evil star"); /* not a bug :o) */

[edit] MAXScript

fn reverseString s =
(
local reversed = ""
for i in s.count to 1 by -1 do reversed += s[i]
reversed
)

[edit] Mirah

def reverse(s:string) 
StringBuilder.new(s).reverse
end
 
puts reverse('reversed')

[edit] Modula-3

MODULE Reverse EXPORTS Main;
 
IMPORT IO, Text;
 
PROCEDURE String(item: TEXT): TEXT =
VAR result: TEXT := "";
BEGIN
FOR i := Text.Length(item) - 1 TO 0 BY - 1 DO
result := Text.Cat(result, Text.FromChar(Text.GetChar(item, i)));
END;
RETURN result;
END String;
 
BEGIN
IO.Put(String("Foobarbaz") & "\n");
END Reverse.
Output:
zabrabooF

[edit] MUMPS

REVERSE
 ;Take in a string and reverse it using the built in function $REVERSE
NEW S
READ:30 "Enter a string: ",S
WRITE !,$REVERSE(S)
QUIT
Output:
USER>D REVERSE^ROSETTA
Enter a string: Hello, World!
!dlroW ,olleH

[edit] Nemerle

[edit] Supporting Combining Characters

Compile with:
ncc -reference:System.Windows.Forms reverse.n
using System;
using System.Globalization;
using System.Windows.Forms;
using System.Console;
using Nemerle.Utility.NString;
 
module StrReverse
{
UReverse(text : string) : string
{
mutable output = [];
def elements = StringInfo.GetTextElementEnumerator(text);
while (elements.MoveNext())
output ::= elements.GetTextElement().ToString();
Concat("", output.Reverse());
}
 
Main() : void
{
def test = "as⃝df̅";
MessageBox.Show($"$test --> $(UReverse(test))"); //for whatever reason my console didn't display Unicode properly, but a MessageBox worked
}
}

[edit] Basic Reverse

Doesn't require the System.Globalization namespace, probably a little less overhead.

Reverse(text : string) : string
{
mutable output = [];
foreach (c in text.ToCharArray())
output ::= c.ToString();
Concat("", output)
}

[edit] NetRexx

/* NetRexx */
 
options replace format comments java crossref savelog symbols nobinary
 
reverseThis = 'asdf'
sihTesrever = reverseThis.reverse
 
say reverseThis
say sihTesrever
 
return
Output:
asdf
fdsa

[edit] Nial

reverse 'asdf'
=fdsa

[edit] Nimrod

import unicode
 
proc reverse(s: var string) =
for i in 0 .. s.high div 2:
swap(s[i], s[s.high - i])
 
proc reversed(s: string): string =
result = newString(s.len)
for i,c in s:
result[s.high - i] = c
 
proc uniReversed(s: string): string =
result = newStringOfCap(s.len)
var tmp: seq[TRune] = @[]
for r in runes(s):
tmp.add(r)
for i in countdown(tmp.high, 0):
result.add(toUtf8(tmp[i]))
 
proc isComb(r: TRune): bool =
(r >=% TRune(0x300) and r <=% TRune(0x36f)) or
(r >=% TRune(0x1dc0) and r <=% TRune(0x1dff)) or
(r >=% TRune(0x20d0) and r <=% TRune(0x20ff)) or
(r >=% TRune(0xfe20) and r <=% TRune(0xfe2f))
 
proc uniReversedPreserving(s: string): string =
result = newStringOfCap(s.len)
var tmp: seq[TRune] = @[]
for r in runes(s):
if isComb(r): tmp.insert(r, tmp.high)
else: tmp.add(r)
for i in countdown(tmp.high, 0):
result.add(toUtf8(tmp[i]))
 
for str in ["Reverse This!", "as⃝df̅"]:
echo "Original string: ", str
echo "Reversed: ", reversed(str)
echo "UniReversed: ", uniReversed(str)
echo "UniReversedPreserving: ", uniReversedPreserving(str)
Output:
Original string:       Reverse This!
Reversed:              !sihT esreveR
UniReversed:           !sihT esreveR
UniReversedPreserving: !sihT esreveR
Original string:       as⃝df̅
Reversed:              Ìfdâsa
UniReversed:          ‾fd⃝sa
UniReversedPreserving: f̅ds⃝a

[edit] NewLISP

(reverse "!dlroW olleH")

[edit] Objeck

 
result := "asdf"->Reverse();
 

[edit] Objective-C

This extends the NSString object adding a reverseString class method.

#import <Foundation/Foundation.h>
 
@interface NSString (Extended)
-(NSString *)reverseString;
@end
 
@implementation NSString (Extended)
-(NSString *) reverseString
{
NSUInteger len = [self length];
NSMutableString *rtr=[NSMutableString stringWithCapacity:len];
// unichar buf[1];
 
while (len > (NSUInteger)0) {
unichar uch = [self characterAtIndex:--len];
[rtr appendString:[NSString stringWithCharacters:&uch length:1]];
}
return rtr;
}
@end

Usage example:

int main()
{
@autoreleasepool {
 
NSString *test = [@"!A string to be reverted!" reverseString];
 
NSLog(@"%@", test);
 
}
return 0;
}

[edit] Supporting combining characters

Extra credit

#import <Foundation/Foundation.h>
 
@interface NSString (Extended)
-(NSString *)reverseString;
@end
 
@implementation NSString (Extended)
-(NSString *)reverseString
{
NSInteger l = [self length] - 1;
NSMutableString *ostr = [NSMutableString stringWithCapacity:[self length]];
while (l >= 0)
{
NSRange range = [self rangeOfComposedCharacterSequenceAtIndex:l];
[ostr appendString:[self substringWithRange:range]];
l -= range.length;
}
return ostr;
}
@end

Usage example:

int main()
{
@autoreleasepool {
 
NSString *test = [@"as⃝df̅" reverseString];
 
NSLog(@"%@", test);
 
}
return 0;
}

[edit] OCaml

Here a version that returns a new allocated string (preserving the original one):

let rev_string str =
let len = String.length str in
let res = String.create len in
let last = len - 1 in
for i = 0 to last do
let j = last - i in
res.[i] <- str.[j];
done;
(res)

and here with in place modification:

let rev_string str =
let last = String.length str - 1 in
for i = 0 to last / 2 do
let j = last - i in
let c = str.[i] in
str.[i] <- str.[j];
str.[j] <- c;
done

here is a 100% functionnal string reversing function:

let rec revs strin list index =
if List.length list = String.length strin
then String.concat "" list
else revs strin ((String.sub strin index 1)::list) (index+1)

revs "Hello World!" [] 0 will return "!dlroW olleH"

[edit] Octave

s = "a string";
rev = s(length(s):-1:1)

[edit] OpenEdge/Progress

FUNCTION reverseString RETURNS CHARACTER (
INPUT i_c AS CHARACTER
):
 
DEFINE VARIABLE cresult AS CHARACTER NO-UNDO.
DEFINE VARIABLE ii AS INTEGER NO-UNDO.
 
DO ii = LENGTH( i_c ) TO 1 BY -1:
cresult = cresult + SUBSTRING( i_c, ii, 1 ).
END.
RETURN cresult.
 
END FUNCTION.
 
MESSAGE reverseString( "asdf" ) VIEW-AS ALERT-BOX.

[edit] OOC

 
main: func {
"asdf" reverse() println() // prints "fdsa"
}
 

[edit] OxygenBasic

 
 
'8 BIT CHARACTERS
 
string s="qwertyuiop"
sys a,b,i,j,le=len s
'
for i=1 to le
j=le-i+1
if j<=i then exit for
a=asc s,i
b=asc s,j
mid s,j,chr a
mid s,i,chr b
next
'
 
print s
 
'16 BIT CHARACTERS
 
wstring s="qwertyuiop"
sys a,b,i,j,le=len s
'
for i=1 to le
j=le-i+1
if j<=i then exit for
a=unic s,i
b=unic s,j
mid s,j,wchr a
mid s,i,wchr b
next
'
print s
 

[edit] OxygenBasic x86 Assembler

32 bit code, 8-bit characters:

 
 
string s="qwertyuiop"
sys p=strptr s, le=len s
mov esi,p
mov edi,esi
add edi,le
dec edi
(
cmp esi,edi
jge exit
mov al,[esi]
mov ah,[edi]
mov [esi],ah
mov [edi],al
inc esi
dec edi
repeat
)
 
print s
 

[edit] Oz

Strings are lists. A function "Reverse" defined on lists is part of the implementation.

{System.showInfo {Reverse "!dlroW olleH"}}

An efficient (tail-recursive) implementation could look like this:

local
fun {DoReverse Xs Ys}
case Xs of nil then Ys
[] X|Xr then {DoReverse Xr X|Ys}
end
end
in
fun {Reverse Xs} {DoReverse Xs nil} end
end

Oz uses a single-byte encoding by default. If you decide to use a multi-byte encoding, Reverse will not work correctly.

[edit] PARI/GP

reverse(s)=concat(Vecrev(s))

[edit] Pascal

The following examples handle correctly only single-byte encodings.

[edit] Standard Pascal

The following only works on implementations which implement Level 1 of standard Pascal (many popular compilers don't).

Standard Pascal doesn't have a separate string type, but uses arrays of char for strings. Note that Standard Pascal doesn't allow a return type of char array, therefore the destination array is passed through a var parameter (which is more efficient anyway).

{ the result array must be at least as large as the original array }
procedure reverse(s: array[min .. max: integer] of char, var result: array[min1 .. max1: integer] of char);
var
i, len: integer;
begin
len := max-min+1;
for i := 0 to len-1 do
result[min1 + len-1 - i] := s[min + i]
end;
{Copy and paste it in your program}
function revstr(my_s:string):string;
var out_s:string;
ls,i:integer;
begin
ls:=length(my_s);
for i:=1 to ls do
out_s:=out_s+my_s[ls-i+1];
revstr:=out_s;
end;

[edit] Extended Pascal, Turbo Pascal, Delphi and compatible compilers

function reverse(s:string):string;
var i:integer;
var tmp:char;
begin
for i:=1 to length(s) div 2 do
begin
tmp:=s[i];
s[i]:=s[length(s)+1-i];
s[length(s)+1-i]:=tmp;
reverse:=s;
end;
end;

[edit] Perl

This reverses characters (code points):

$string = "visor";
$flip = reverse $string; # becomes "rosiv"

This reverses graphemes:

$string = "Jose\x{301}"; # "José" in NFD
$flip = join("", reverse $string =~ /\X/g); # becomes "ésoJ"

[edit] Perl 6

# Not transformative.
my $reverse = flip $string;
# or
say "hello world".flip;

Perl 6 is specced to work on graphemes by default, but current implementations are limited to processing codepoints.

[edit] PHP

strrev($string);

If you want Unicode support, you have to use some multibyte function. Sadly, PHP doesn't contain mb_strrev(). One of functions which support Unicode and is useful in this case is preg_split().

// Will split every Unicode character to array, reverse array and will convert it to string.
join('', array_reverse(preg_split('""u', $string, -1, PREG_SPLIT_NO_EMPTY)));

[edit] PicoLisp

(pack (flip (chop "äöüÄÖÜß")))
Output:
-> "ßÜÖÄüöä"

[edit] PL/I

s = reverse(s);

[edit] Pop11

define reverse_string(s);
lvars i, l = length(s);
for i from l by -1 to 1 do
s(i);
endfor;
consstring(l);
enddefine;

[edit] PostScript

The following implementation works on arrays of numerics as well as characters ( string ).

/reverse{
/str exch def
/temp str 0 get def
/i 0 def
str length 2 idiv{
/temp str i get def
str i str str length i sub 1 sub get put
str str length i sub 1 sub temp put
/i i 1 add def
}repeat
str pstack
}def

Output is as below:

[1 2 3] reverse % input
[3 2 1]
 
(Hello World) reverse % input
(dlroW olleH)

[edit] PowerShell

Test string

$s = "asdf"

[edit] Array indexing

Creating a character array from the end to the string's start and join it together into a string again.

Works with: PowerShell version 1
[string]::Join('', $s[$s.Length..0])
Works with: PowerShell version 2
-join ($s[$s.Length..0])
Works with: PowerShell version 2
[array]::Reverse($s)

[edit] Regular expressions

Creating a regular expression substitution which captures every character of the string in a capture group and uses a reverse-ordered string of references to those to construct the reversed string.

Works with: PowerShell version 1
$s -replace
('(.)' * $s.Length),
[string]::Join('', ($s.Length..1 | ForEach-Object { "`$$_" }))
Works with: PowerShell version 2
$s -replace
('(.)' * $s.Length),
-join ($s.Length..1 | ForEach-Object { "`$$_" } )

[edit] Prolog

Works with: SWI Prolog
reverse("abcd", L), string_to_list(S,L).
output :
L = [100,99,98,97],
S = "dcba".

The main workings are hidden inside the reverse/2 predicate, so lets write one to see how it works:

accRev([H|T], A, R) :- accRev(T, [H|A], R).
accRev([], A, A).
 
rev(L,R) :- accRev(L,[],R).

[edit] Protium

Padded out, variable length Chinese dialect

<# 显示 指定 变量 反转顺序 字串>集装箱|猫坐在垫子</#>
This assigns the reverse of 'the cat sat on the mat' to the variable 'container' and displays the result which is
子垫在坐猫
which Google Translate renders as
Sub-pad sitting cat
.

The same again but with everything in Korean.

<# 보이십 할당하 변물건 열거꾸 문자그>컨테이너|고양이가 매트 위에 앉아</#>
Reversing the Korean makes an untranslatable-by-Google mess of the sentence, viz
아앉 에위 트매 가이양고
.

The short-opcode version in English dialect is

<@ SAYLETVARREVLIT>集装箱|猫坐在垫子</@>

Protium works in Unicode.

[edit] PureBasic

Debug ReverseString("!dekrow tI")

[edit] Python

[edit] Optimized for user input

raw_input()[::-1]

[edit] Already known string

string[::-1]

[edit] Unicode reversal

(See this article for more information)

'''
Reverse a Unicode string with proper handling of combining characters
'''

 
import unicodedata
 
def ureverse(ustring):
'''
Reverse a string including unicode combining characters
 
Example:
>>> ucode = ''.join( chr(int(n, 16))
for n in ['61', '73', '20dd', '64', '66', '305'] )
>>> ucoderev = ureverse(ucode)
>>> ['%x' % ord(char) for char in ucoderev]
['66', '305', '64', '73', '20dd', '61']
>>>
'''

groupedchars = []
uchar = list(ustring)
while uchar:
if 'COMBINING' in unicodedata.name(uchar[0], ''):
groupedchars[-1] += uchar.pop(0)
else:
groupedchars.append(uchar.pop(0))
# Grouped reversal
groupedchars = groupedchars[::-1]
 
return ''.join(groupedchars)
 
if __name__ == '__main__':
ucode = ''.join( chr(int(n, 16))
for n in ['61', '73', '20dd', '64', '66', '305'] )
ucoderev = ureverse(ucode)
print (ucode)
print (ucoderev)

[edit] Qi

It's simplest just to use the common lisp REVERSE function.

(REVERSE "ABCD")

[edit] R

Works with: R version 2.8.1

The following code works with UTF-8 encoded strings too.

revstring <- function(stringtorev) {
return(
paste(
strsplit(stringtorev,"")[[1]][nchar(stringtorev):1]
,collapse="")
)
}

Alternatively (using rev() function):

 revstring <- function(s) paste(rev(strsplit(s,"")[[1]]),collapse="")
revstring("asdf")
revstring("m\u00f8\u00f8se")
Encoding("m\u00f8\u00f8se") # just to check if on your system it's something
# different!
Output:
[1] "fdsa"
[1] "esøøm"
[1] "UTF-8"

R can encode strings in Latin1 and UTF-8 (the default may depend on the locale); the Encoding(string) can be used to know if the string is encoded in Latin1 or UTF-8; the encoding can be forced (Encoding(x) <- "latin1"), or we can use iconv to properly translate between encodings whenever possible.

[edit] Rascal

import String;
reverse("string")

[edit] Racket

As in Scheme:

#lang racket
 
(define (string-reverse s)
(list->string (reverse (string->list s))))
 
(string-reverse "aoeu")
Output:
Welcome to DrRacket, version 5.3.3.5--2013-02-20(5eddac74/d) [3m].
Language: racket; memory limit: 512 MB.
"ueoa"
> 

[edit] Raven

"asdf" reverse
Output:
fdsa

[edit] REBOL

print reverse "asdf"

Note the string is reversed in place. If you were using it anywhere else, you would find it reversed:

x: "asdf"
print reverse x
print x ; Now reversed.

REBOL/View 2.7.6.3.1 14-Mar-2008 does not handle Unicode strings. This is planned for REBOL 3.

[edit] Retro

with strings'
"asdf" reverse puts

[edit] REXX

All methods shown below also work with   NULL   values.

[edit] using REVERSE bif

/*REXX program to reverse a string  (and show before and after strings).*/
 
string1 = 'A man, a plan, a canal, Panama!'
string2 = reverse(string1)
 
say ' original string: ' string1
say ' reversed string: ' string2
/*stick a fork in it, we're done.*/

output

 original string:  A man, a plan, a canal, Panama!
 reversed string:  !amanaP ,lanac a ,nalp a ,nam A

[edit] using SUBSTR bif, left to right

/*REXX program to reverse a string  (and show before and after strings).*/
 
string1 = 'A man, a plan, a canal, Panama!'
string2 =
do j=1 for length(string1)
string2 = substr(string1,j,1)string2
end /*j*/
say ' original string: ' string1
say ' reversed string: ' string2
/*stick a fork in it, we're done.*/

output is identical to the 1st version.

(Regarding the previous example)   Another method of coding an abutment (an implied concatenation) is:

                                   string2 = substr(string1,j,1) || string2
/*───── or ─────*/
string2=substr(string1,j,1)||string2

[edit] using SUBSTR bif, right to left

/*REXX program to reverse a string  (and show before and after strings).*/
 
string1 = 'A man, a plan, a canal, Panama!'
string2 =
do j=length(string1) to 1 by -1
string2 = string2 || substr(string1,j,1)
end /*j*/
say ' original string: ' string1
say ' reversed string: ' string2
/*stick a fork in it, we're done.*/

output is identical to the 1st version.

[edit] RLaB

>> x = "rosettacode"
rosettacode
 
// script
rx = "";
for (i in strlen(x):1:-1)
{
rx = rx + substr(x, i);
}
 
>> rx
edocattesor

[edit] Ruby

str = "asdf"
reversed = str.reverse

or

#encoding: utf-8
"résumé niño".reverse #=> "oñin émusér"

[edit] Run BASIC

string$ = "123456789abcdefghijk"
for i = len(string$) to 1 step -1
print mid$(string$,i,1);
next i

[edit] Rust

// rust 0.9
let s = "一二三四五六七八九十";
let reversed:~str = s.chars_rev().collect();

or

let reversed:~str = "一二三四五六七八九十".chars_rev().collect(); 

[edit] SAS

data _null_;
length a b $11;
a="I am Legend";
b=reverse(a);
put a;
put b;
run;

[edit] Sather

class MAIN is
main is
s ::= "asdf";
reversed ::= s.reverse;
-- current implementation does not handle multibyte encodings correctly
end;
end;

[edit] Scala

Easy way:

"asdf".reverse

Slightly less easy way:

"asdf".foldRight(""){ (a,b)=> b+a } 

Unicode-aware. I can't guarantee it get all the cases, but it does work with combining characters as well as supplementary characters. I did not bother to preserve the order of newline characters, and I didn't even consider directionality beyond just ruling it out.

def reverseString(s: String) = {
import java.lang.Character._
 
val combiningTypes = List(NON_SPACING_MARK, ENCLOSING_MARK, COMBINING_SPACING_MARK)
def isCombiningCharacter(c: Char) = combiningTypes contains c.getType
def isCombiningSurrogate(high: Char, low: Char) = combiningTypes contains getType(toCodePoint(high, low))
def isCombining(l: List[Char]) = l match {
case List(a, b) => isCombiningSurrogate(a, b)
case List(a) => isCombiningCharacter(a)
case Nil => true
case _ => throw new IllegalArgumentException("isCombining expects a list of up to two characters")
}
 
def cleanSurrogate(l: List[Char]) = l match {
case List(a, b) if a.isHighSurrogate && b.isLowSurrogate => l
case List(a, b) if a.isLowSurrogate => Nil
case List(a, b) => List(a)
case _ => throw new IllegalArgumentException("cleanSurrogate expects lists of two characters, exactly")
}
 
def splitString(string: String) = (string+" ").iterator sliding 2 map (_.toList) map cleanSurrogate toList
 
def recurse(fwd: List[List[Char]], rev: List[Char]): String = fwd match {
case Nil => rev.mkString
case c :: rest =>
val (combining, remaining) = rest span isCombining
recurse(remaining, c ::: combining.foldLeft(List[Char]())(_ ::: _) ::: rev)
}
recurse(splitString(s), Nil)
}

REPL on Windows doesn't handle Unicode, so I'll show the bytes instead:

scala> res71 map ("\\u%04x" format _.toInt)
res80: scala.collection.immutable.IndexedSeq[String] = IndexedSeq(\u0061, \u0073, \u20dd, \u0064, \u0066, \u0305)

scala> reverseString(res71) map ("\\u%04x" format _.toInt)
res81: scala.collection.immutable.IndexedSeq[String] = IndexedSeq(\u0066, \u0305, \u0064, \u0073, \u20dd, \u0061)

[edit] Scheme

(define (string-reverse s)
(list->string (reverse (string->list s))))
> (string-reverse "asdf")
"fdsa"

[edit] Scratch

ScratchReverseAString.png

[edit] Sed

#!/bin/sed -f
 
/../! b
 
# Reverse a line. Begin embedding the line between two newlines
s/^.*$/\
&\
/
 
# Move first character at the end. The regexp matches until
# there are zero or one characters between the markers
tx
:x
s/\(\n.\)\(.*\)\(.\n\)/\3\2\1/
tx
 
# Remove the newline markers
s/\n//g

[edit] Seed7

Seed7 strings are encoded with UTF-32 therefore no special Unicode solution is necessary

$ include "seed7_05.s7i";
 
const func string: reverse (in string: stri) is func
result
var string: result is "";
local
var integer: index is 0;
begin
for index range length(stri) downto 1 do
result &:= stri[index];
end for;
end func;
 
const proc: main is func
begin
writeln(reverse("Was it a cat I saw"));
end func;
Output:
was I tac a ti saW

[edit] Sidef

"asdf".reverse;             # fdsa
"résumé niño".reverse; # oñin émusér

[edit] Slate

In-place reversal:

'asdf' reverse

Non-destructive reversal:

'asdf' reversed

[edit] Smalltalk

'asdf' reverse
Works with: Smalltalk/X

the above does inplace, destructive reverse. It is usually better to use

'asdf' reversed

which returns a new string.

[edit] SNOBOL4

ASCII-only

	output = reverse(reverse("reverse"))
end

{{out}

reverse

[edit] Standard ML

val str_reverse = implode o rev o explode;
val string = "asdf";
val reversed = str_reverse string;

[edit] Swift

Swift's strings are iterated by Characters, which represent "Unicode grapheme clusters", so reversing it reverses it with combining characters too:

func reverseString(s: String) -> String {
var result = ""
result.extend(reverse(s))
return result
}
println(reverseString("asdf"))
println(reverseString("as⃝df̅"))
Output:
fdsa
f̅ds⃝a

[edit] Tcl

package require Tcl 8.5
string reverse asdf

[edit] TI-83 BASIC

The following program will place the reverse of Str1 in Str0. Note: length( and sub( can be found in the catalog.

:"ASDF"→Str1
:
:" "→Str0
:length(Str1)→B
:For(A,B,1,-1)
:Str0+sub(Str1,A,1)→Str0
:End
:sub(Str0,2,B)→Str0

The reason a single space must be placed in Str0 and then later removed is that for some reason, the TI-83 will not allow concatenation with an empty string (so Str0+sub... would fail).

[edit] Turing

 
% Reverse a string
 
var input : string (100)
 
put "Enter a string to reverse: " ..
get input
 
var count : int := length(input)
loop
if count >= 1 then
put input(count) ..
else
exit
end if
count := count - 1
end loop
 

[edit] TUSCRIPT

$$ MODE TUSCRIPT
SET input="was it really a big fat cat i saw"
SET reversetext=TURN (input)
PRINT "before: ",input
PRINT "after: ",reversetext
Output:
before: was it really a big fat cat i saw
after:  was i tac taf gib a yllaer ti saw   

[edit] UNIX Shell

 
#!/bin/bash
str=abcde
 
for((i=${#str}-1;i>=0;i--)); do rev="$rev${str:$i:1}"; done
 
echo $rev
 

[edit] Unlambda

Reverse the whole input:

``@c`d``s`|k`@c

[edit] Ursala

#import std
 
#cast %s
 
example = ~&x 'asdf'
 
verbose_example = reverse 'asdf'
Output:
'fdsa'

[edit] VBA

[edit] Non-recursive version

Public Function Reverse(aString as String) as String
' returns the reversed string
dim L as integer 'length of string
dim newString as string
 
newString = ""
L = len(aString)
for i = L to 1 step -1
newString = newString & mid$(aString, i, 1)
next
Reverse = newString
End Function

[edit] Recursive version

Public Function RReverse(aString As String) As String
'returns the reversed string
'do it recursively: cut the string in two, reverse these fragments and put them back together in reverse order
Dim L As Integer 'length of string
Dim M As Integer 'cut point
 
L = Len(aString)
If L <= 1 Then 'no need to reverse
RReverse = aString
Else
M = Int(L / 2)
RReverse = RReverse(Right$(aString, L - M)) & RReverse(Left$(aString, M))
End If
End Function

[edit] Example dialogue

print Reverse("Public Function Reverse(aString As String) As String")
gnirtS sA )gnirtS sA gnirtSa(esreveR noitcnuF cilbuP

print RReverse("Sunday Monday Tuesday Wednesday Thursday Friday Saturday Love")
evoL yadrutaS yadirF yadsruhT yadsendeW yadseuT yadnoM yadnuS

print RReverse(Reverse("I know what you did last summer"))
I know what you did last summer

[edit] VBScript

Works with: Windows Script Host version *
 
WScript.Echo StrReverse("asdf")
 

[edit] Vedit macro language

This routine reads the text from current line, reverses it and stores the reversed string in text register 10:

Reg_Empty(10)
for (BOL; !At_EOL; Char) {
Reg_Copy_Block(10, CP, CP+1, INSERT)
}

This routine reverses the current line in-place:

BOL
while (!At_EOL) {
Block_Copy(EOL_pos-1, EOL_pos, DELETE)
}

[edit] Visual Basic .NET

  Function Reverse(ByVal s As String) As String
Dim t() as Char = s.toCharArray
Array.reverse(t)
Return new String(t)
End Function

[edit] Wart

(rev "asdf")

Wart doesn't support unicode yet.

[edit] Wortel

; the @rev operator reverses strings and arrays
@rev "abc" ; returns "cba"
; or the same thing using a pointer expression
!~r "abc"

[edit] XPL0

include c:\cxpl\codes;  \intrinsic 'code' declarations
string 0; \use zero-terminated strings, instead of MSb terminated
 
func StrLen(Str); \Return the number of characters in an ASCIIZ string
char Str;
int I;
for I:= 0 to -1>>1-1 do
if Str(I) = 0 then return I;
 
func RevStr(S); \Reverse the order of the bytes in a string
char S;
int L, I, T;
[L:= StrLen(S);
for I:= 0 to L/2-1 do
[T:= S(I); S(I):= S(L-I-1); S(L-I-1):= T];
return S;
];
 
[Text(0, RevStr("a")); CrLf(0);
Text(0, RevStr("ab")); CrLf(0);
Text(0, RevStr("abc")); CrLf(0);
Text(0, RevStr("Able was I ere I saw Elba.")); CrLf(0);
]

Output:

a
ba
cba
.ablE was I ere I saw elbA

[edit] Yorick

This only handles ASCII characters. It works by converting a string to an array of char; dropping the last character (which is the null byte); reversing the order of the characters; then converting back to a string.

strchar(strchar("asdf")(:-1)(::-1))

[edit] zkl

These only handle ASCII characters, no extra credit.

"this is a test".reverse()

Old school ways to do it:

Build by prepending characters, creates n strings:

"this is a test".reduce(fcn(p,c){c+p})

Convert to list, reverse, convert back to string:

"this is a test".split("").reverse().concat()

Write to a byte buffer and convert to string:

"this is a test".pump(Void,Data().insert.fp(0)).text

The ".fp(0)" creates a closure so each character is fed to data.insert(0,c). pump is a method that sends each character to a function to a sink (in this case /dev/null). The output is the result of the last call, which is data.insert which is self/data.

Personal tools
Namespaces

Variants
Actions
Community
Explore
Misc
Toolbox