Reverse a string
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
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".
ActionScript
<lang 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(); } </lang>
Ada
<lang 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;</lang>
ALGOL 68
<lang algol68>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))
)</lang> Output:
was I tac a ti saW
APL
<lang apl> ⌽'asdf' fdsa</lang>
AppleScript
<lang 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</lang>
AutoHotkey
<lang AutoHotkey>MsgBox % reverse("asdf")
reverse(string) {
Loop, Parse, string reversed := A_LoopField . reversed Return reversed
}</lang>
AutoIt
<lang 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) </lang>
AWK
<lang awk>function reverse(s) {
p = "" for(i=length(s); i > 0; i--) { p = p substr(s, i, 1) } return p
}
BEGIN {
print reverse("edoCattesoR")
}</lang>
BASIC
<lang qbasic>function reverse$(a$)
b$ = "" for i = 1 to len(a$) b$ = mid$(a$, i, 1) + b$ next i reverse$ = b$
end function</lang>
Batch File
<lang dos>@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</lang>
BBC BASIC
<lang bbcbasic> 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$</lang>
Befunge
To see this in action, it's best to use an interpreter that animates the process.
<lang befunge>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.</lang>
Brainf***
<lang bf>[-]>,+[->,+]<[.<]</lang>
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
<lang bf>,----- ----- [+++++ +++++ > , ----- -----] 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 +++++ +++++ +++ . --- .</lang>
Brat
<lang brat>p "olleh".reverse #Prints "hello"</lang>
C
<lang c>#include <stdio.h>
/* This function assumes the passed pointer points to a valid, zero-terminated string */ void reverse (char *s) {
char *t = s;
while (*t != '\0') t++; while (s < t) { int c = *s; *s++ = *--t; *t = c; }
}
int main () {
char text1[] = "asdf", text2[] = ""; reverse (text1); printf ("'%s'\n", text1); reverse (text2); printf ("'%s'\n", text2);
return 0;
}</lang>
C++
<lang cpp>#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;
}</lang>
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: <lang csharp>private static string ReverseString(string input) { char[] inputChars = input.ToCharArray(); Array.Reverse(inputChars); return new string(inputChars); }</lang>
As of C# 4.0 you can call the Reverse method on a string, however it returns an Enumerable of chars. It appears that this only helps by letting you do the above in a different order (reverse the string, convert that to an array of chars, and return a new string from the reversed array):
<lang csharp>return new string(input.Reverse().ToArray());</lang>
Clojure
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.
<lang lisp>(defn str-reverse [s] (apply str (reverse s)))</lang>
Reverse words in a string
<lang lisp>(apply str (interpose " " (reverse (.split "the quick brown fox" " "))))</lang>
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.
<lang lisp>(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)))))</lang>
And the test result:
user=> s "as⃝df̅" user=> (str-reverse s) "f̅ds⃝a"[ user=> (str-reverse (str-reverse s)) "as⃝df̅" user=>
CoffeeScript
<lang javascript> "qwerty".split("").reverse().join "" </lang>
ColdFusion
You can reverse anything that can be written to the document in hashmarks (i.e. strings, numbers, now( ), etc.). <lang cfm><cfset myString = "asdf" /> <cfset myString = reverse( myString ) /></lang>
Common Lisp
<lang lisp>(reverse my-string)</lang>
D
D has a built-in reverse function for array types (including string=char[]). It is an in-place function. <lang d>string s ; s.reverse ; s.dup.reverse ; // preserve original array</lang>
Delphi
<lang Delphi> function ReverseString(const InString: string): string; var
i: integer;
begin
for i := Length(InString) downto 1 do Result := Result + InString[i];
end; </lang>
You could also use this RTL function Introduced in Delphi 6:
<lang Delphi>StrUtils.ReverseString</lang>
E
<lang e>pragma.enable("accumulator") def reverse(string) {
return accum "" for i in (0..!(string.size())).descending() { _ + string[i] }
}</lang>
Emacs Lisp
<lang lisp> (concat (reverse (append "Hello World" nil))) </lang>
Output:
"dlroW olleH"
Eiffel
<lang 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</lang>
Output:
!dlroW olleH
Erlang
<lang erlang>1> lists:reverse("reverse!"). "!esrever"</lang>
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. <lang erlang>reverse(Bin) ->
Size = size(Bin)*8, <<T:Size/integer-little>> = Bin, <<T:Size/integer-big>>.</lang>
Result:
1> test:reverse(<<"hello">>). <<"olleh">>
Euphoria
<lang euphoria> include std/sequence.e printf(1, "%s\n", {reverse("abcdef") }) </lang>
F#
<lang fsharp>let ReverseString (s:string) = new string(Array.rev (s.ToCharArray()))</lang>
Factor
A string is a sequence and there is a default reverse implementation for those.
<lang factor>"hello" reverse</lang>
string-reverse
preserves graphemes:
<lang factor>"as⃝df̅" string-reverse "f̅ds⃝a" = .</lang>
Forth
<lang 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</lang>
Fortran
<lang fortran>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</lang> Output:
This is a string gnirts a si sihT
Another implementation that uses a recursive not-in-place algorithm: <lang fortran>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</lang> Output: <lang>no devil lived on no devil lived on</lang>
Frink
The built-in reverse
function reverses a string or the elements of a list.
<lang frink>
println[reverse["abcdef"]]
</lang>
GAP
<lang gap>Reversed("abcdef");
- "fedcba"</lang>
Gema
Reverse each line in the input stream. Using built in function: <lang gema>\L=@reverse{$1}</lang> Not using built in function (recursively apply substring to same rule): <lang gema>\L<U1>=@{$2}$1</lang>
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 made easy work of recognizing combining characters for this task. <lang go>package main
import (
"fmt" "unicode"
)
// 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)
}
// argument and return value are UTF-8 func reverseCodePoints(s string) string {
r := make([]int, len(s)) start := len(s) for _, c := range s { start-- r[start] = c } return string(r[start:])
}
// argument and return value are UTF-8 func reversePreservingCombiningCharacters(s string) string {
if s == "" { return "" } p := []int(s) r := make([]int, len(p)) for i := 0; i < len(p); { 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 := i; k < j; k++ {
r[len(r)-j+k-i] = p[k] } i = j } return (string(r))
}
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:", []int(s), s) r = reverseCodePoints(s) fmt.Println("reversed code points:", []int(r), r) r = reversePreservingCombiningCharacters(s) fmt.Println("combining characters:", []int(r), r)
}</lang> 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
Groovy
Solution: <lang groovy>println "Able was I, 'ere I saw Elba.".reverse()</lang> Output:
.ablE was I ere' ,I saw elbA
Haskell
<lang haskell>reverse = foldl (flip (:)) []</lang> This function in defined in the Haskell Prelude.
Supporting combining characters
<lang haskell>import Data.Char (isMark) import Data.List (groupBy) myReverse = concat . reverse . groupBy (const isMark)</lang>
groupBy (const isMark)
is an unusual way of splitting a string into its combined characters
HicEst
<lang 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 </lang>
Icon and Unicon
<lang Icon>procedure main(arglist) s := \arglist[1] | "asdf" write(s," <-> ", reverse(s)) # reverse is built-in end</lang>
Io
<lang io>"asdf" reverse</lang>
J
Reverse (|.) reverses a list of items (of any shape or type). <lang j> |.'asdf' fdsa</lang>
Extra credit:
First, a function to determine whether a Unicode character is a combining character:
<lang j> ranges=.16b02ff 16b036f, 16b1dbf 16b1dff, 16b20cf 16b20ff, 16bfe1f 16bfe2f
iscombining=. 2 | ranges&I.</lang>
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. <lang j> split=. (<;.1~ -.@iscombining) :. ;</lang>
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. <lang j> |.&.split&.(3 u: 7&u:) 'as⃝df̅' f̅ds⃝a</lang>
Java
<lang java>public static String reverseString(String s) {
return new StringBuffer(s).reverse().toString();
}</lang>
JavaScript
<lang javascript>var a = "cat".split(""); a.reverse(); print(a.join("")); // tac</lang>
Liberty BASIC
<lang lb>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</lang>
Logo
REVERSE works on both words and lists. <lang logo>print reverse "cat ; tac</lang>
Lua
Built-in string.reverse(s) or s:reverse(). <lang lua>theString = theString:reverse()</lang>
M4
<lang m4>define(`invert',`ifelse(len(`$1'),0,,`invert(substr(`$1',1))'`'substr(`$1',0,1))')</lang>
Mathematica
<lang mathematica>StringReverse["asdf"]</lang>
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: <lang MATLAB>>> fliplr(['She told me that she spoke English and I said great. '... 'Grabbed her hand out the club and I said lets 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 </lang>
MAXScript
<lang maxscript>fn reverseString s = (
local reversed = "" for i in s.count to 1 by -1 do reversed += s[i] reversed
)</lang>
Modula-3
<lang modula3>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.</lang> Output:
zabrabooF
MUMPS
<lang 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
</lang>
Example:
USER>D REVERSE^ROSETTA Enter a string: Hello, World! !dlroW ,olleH
Nial
<lang nial>reverse 'asdf' =fdsa</lang>
Objeck
<lang objeck> result := "asdf"->Reverse(); </lang>
Objective-C
This extends the NSString object adding a reverseString class method.
<lang objc>#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</lang>
Usage example:
<lang objc>int main() {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSString *test = [@"!A string to be reverted!" reverseString]; NSLog(@"%@", test); [pool release]; return 0;
}</lang>
Supporting combining characters
Extra credit
<lang objc>#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</lang>
Usage example:
<lang objc>int main() {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSString *test = [@"as⃝df̅" reverseString]; NSLog(@"%@", test); [pool release]; return 0;
}</lang>
OCaml
Here a version that returns a new allocated string (preserving the original one):
<lang ocaml>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)</lang>
and here with in place modification:
<lang ocaml>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</lang>
here is a 100% functionnal string reversing function:
<lang ocaml>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)</lang>
revs "Hello World!" [] 0 will return "!dlroW olleH"
Octave
<lang octave>s = "a string"; rev = s(length(s):-1:1)</lang>
OpenEdge/Progress
<lang 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. </lang>
Oz
Strings are lists. A function "Reverse" defined on lists is part of the implementation. <lang oz>{System.showInfo {Reverse "!dlroW olleH"}}</lang>
An efficient (tail-recursive) implementation could look like this: <lang oz>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</lang>
Oz uses a single-byte encoding by default. If you decide to use a multi-byte encoding, Reverse will not work correctly.
PARI/GP
<lang parigp> reverse(expr)=my(v=Vec(Str(expr)),n=length(v));concat(vector(n,i,v[n-i+1])); </lang>
Pascal
The following examples handle correctly only single-byte encodings.
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). <lang pascal>{ 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;</lang>
<lang pascal> {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;
</lang>
Extended Pascal, Turbo Pascal, Delphi and compatible compilers
<lang pascal>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;</lang>
Perl
<lang perl>reverse $string</lang>
Perl 6
<lang perl6># Not transformative.
my $reverse = flip $string;
- or
say "hello world".flip;</lang>
PHP
<lang php>strrev($string)</lang>
PicoLisp
<lang PicoLisp>(pack (flip (chop "äöüÄÖÜß")))</lang> Output:
-> "ßÜÖÄüöä"
PL/I
<lang PL/I> s = reverse(s); </lang>
Pop11
<lang 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;</lang>
PostScript
The following implementation works on arrays of numerics as well as characters ( string ).
<lang PostScript> /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 </lang> Output is as below: <lang PostScript> [1 2 3] reverse % input [3 2 1]
(Hello World) reverse % input (dlroW olleH) </lang>
PowerShell
Test string <lang powershell>$s = "asdf"</lang>
Array indexing
Creating a character array from the end to the string's start and join it together into a string again.
<lang powershell>[string]::Join(, $s[$s.Length..0])</lang>
<lang powershell>-join ($s[$s.Length..0])</lang>
<lang powershell>[array]::Reverse($s)</lang>
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.
<lang powershell>$s -replace
('(.)' * $s.Length), [string]::Join(, ($s.Length..1 | ForEach-Object { "`$$_" }))</lang>
<lang powershell>$s -replace
('(.)' * $s.Length), -join ($s.Length..1 | ForEach-Object { "`$$_" } )</lang>
Prolog
Works with SWI-Prolog.
<lang prolog>reverse("abcd", L), string_to_list(S,L).</lang> <lang hml>output : L = [100,99,98,97], S = "dcba". </lang>
Protium
Padded out, variable length Chinese dialect <lang html><# 显示 指定 变量 反转顺序 字串>集装箱|猫坐在垫子</#></lang>
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. <lang html><# 보이십 할당하 변물건 열거꾸 문자그>컨테이너|고양이가 매트 위에 앉아</#></lang>
Reversing the Korean makes an untranslatable-by-Google mess of the sentence, viz
아앉 에위 트매 가이양고
.
The short-opcode version in English dialect is <lang html><@ SAYLETVARREVLIT>集装箱|猫坐在垫子</@></lang>
Protium works in Unicode.
PureBasic
<lang PureBasic>Debug ReverseString("!dekrow tI")</lang>
Python
Optimized for user input
<lang python>raw_input()[::-1]</lang>
Already known string
<lang python>string[::-1]</lang>
Unicode reversal
(See this article for more information)
<lang python>
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)</lang>
R
The following code works with UTF-8 encoded strings too. <lang R>revstring <- function(stringtorev) {
return( paste( strsplit(stringtorev,"")1[nchar(stringtorev):1] ,collapse="") )
} revstring("asdf") revstring("m\u00f8\u00f8se") Encoding("m\u00f8\u00f8se") # just to check if on your system it's something
# different!</lang>
Outputs
[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.
REBOL
<lang REBOL>print reverse "asdf"</lang>
Note the string is reversed in place. If you were using it anywhere else, you would find it reversed:
<lang REBOL>x: "asdf" print reverse x print x ; Now reversed.</lang>
REBOL/View 2.7.6.3.1 14-Mar-2008 does not handle Unicode strings. This is planned for REBOL 3.
Retro
<lang Retro> with strings' "asdf" reverse puts </lang>
REXX
<lang rexx> p='A man, a plan, a canal, Panama!' q=reverse(p) say p say q </lang> Output:
A man, a plan, a canal, Panama! !amanaP ,lanac a ,nalp a ,nam A
RLaB
<lang RLaB> >> x = "rosettacode" rosettacode
// script rx = ""; for (i in strlen(x):1:-1) {
rx = rx + substr(x, i);
}
>> rx edocattesor
</lang>
Ruby
<lang ruby>str = "asdf" reversed = str.reverse</lang>
Sather
<lang sather>class MAIN is
main is s ::= "asdf"; reversed ::= s.reverse; -- current implementation does not handle multibyte encodings correctly end;
end;</lang>
Scala
Easy way:
<lang scala>"asdf".reverse</lang>
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.
<lang scala>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)
}</lang>
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)
Scheme
<lang scheme>(define (string-reverse s)
(list->string (reverse (string->list s))))</lang>
> (string-reverse "asdf") "fdsa"
Seed7
Seed7 strings are encoded with UTF-32 therefore no special Unicode solution is necessary
<lang seed7>$ 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;</lang>
Output:
was I tac a ti saW
Slate
In-place reversal: <lang slate>'asdf' reverse</lang> Non-destructive reversal: <lang slate>'asdf' reversed</lang>
Smalltalk
<lang smalltalk>'asdf' reverse</lang>
SNOBOL4
ASCII-only <lang snobol> output = reverse(reverse("reverse")) end</lang>
output: <lang>reverse</lang>
Standard ML
<lang sml>val str_reverse = implode o rev o explode; val string = "asdf"; val reversed = str_reverse string;</lang>
Tcl
<lang tcl>package require Tcl 8.5 string reverse asdf</lang>
TI-83 BASIC
The following program will place the reverse of Str1 in Str0. Note: length( and sub( can be found in the catalog. <lang ti83b>:"ASDF"→Str1
- " "→Str0
- length(Str1)→B
- For(A,B,1,-1)
- Str0+sub(Str1,A,1)→Str0
- End
- sub(Str0,2,B)→Str0</lang>
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).
TUSCRIPT
<lang tuscript> $$ MODE TUSCRIPT SET input="was it really a big fat cat i saw" SET reversetext=TURN (input) PRINT "before: ",input PRINT "after: ",reversetext </lang> Output:
before: was it really a big fat cat i saw after: was i tac taf gib a yllaer ti saw
Ursala
<lang Ursala>#import std
- cast %s
example = ~&x 'asdf'
verbose_example = reverse 'asdf'</lang> output:
'fdsa'
Vedit macro language
This routine reads the text from current line, reverses it and stores the reversed string in text register 10:
<lang vedit>Reg_Empty(10) for (BOL; !At_EOL; Char) {
Reg_Copy_Block(10, CP, CP+1, INSERT)
}</lang>
This routine reverses the current line in-place:
<lang vedit>BOL while (!At_EOL) {
Block_Copy(EOL_pos-1, EOL_pos, DELETE)
}</lang>
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. <lang yorick>strchar(strchar("asdf")(:-1)(::-1))</lang>
Visual Basic .NET
<lang vbnet> Function Reverse(ByVal s As String) As String
Return s.Reverse.ToArray End Function</lang>
- Programming Tasks
- String manipulation
- ActionScript
- Ada
- ALGOL 68
- APL
- AppleScript
- AutoHotkey
- AutoIt
- AWK
- BASIC
- Batch File
- BBC BASIC
- Befunge
- Brainf***
- Brat
- C
- C++
- C sharp
- Clojure
- CoffeeScript
- ColdFusion
- Common Lisp
- D
- Delphi
- E
- E examples needing attention
- Emacs Lisp
- Eiffel
- Erlang
- Euphoria
- F Sharp
- Factor
- Forth
- Fortran
- Frink
- GAP
- Gema
- Go
- Groovy
- Haskell
- HicEst
- Icon
- Unicon
- Io
- J
- Java
- JavaScript
- Liberty BASIC
- Logo
- Lua
- M4
- Mathematica
- MATLAB
- MAXScript
- Modula-3
- MUMPS
- Nial
- Objeck
- Objective-C
- OCaml
- Octave
- OpenEdge/Progress
- Oz
- PARI/GP
- Pascal
- Perl
- Perl 6
- PHP
- PicoLisp
- PL/I
- Pop11
- PostScript
- PowerShell
- Prolog
- Protium
- PureBasic
- Python
- R
- REBOL
- Retro
- REXX
- RLaB
- Ruby
- Sather
- Scala
- Scheme
- Seed7
- Slate
- Smalltalk
- SNOBOL4
- Standard ML
- Tcl
- TI-83 BASIC
- TUSCRIPT
- Ursala
- Vedit macro language
- Yorick
- Bc/Omit
- Dc/Omit
- Visual Basic .NET