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".
0815
This program reverses each line of its input. <lang 0815>}: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.</lang>
- Output:
<lang bash>echo -e "foo\nbar" | 0815 rev.0 oof rab</lang>
ACL2
<lang Lisp>(reverse "hello")</lang>
ACL2 does not support unicode.
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>
Agda2
Using the Agda standard library, version 0.6. <lang agda2>module reverse_string where
open import Data.String open import Data.List
reverse_string : String → String reverse_string s = fromList (reverse (toList s))</lang>
Aime
<lang aime>text reverse(text s) {
data b; integer i;
i = length(s); while (i) { i -= 1; b_insert(b, -1, s[i]); }
return b_string(b);
}
integer main(void) {
o_text(reverse("Hello, World!")); o_byte('\n');
return 0;
}</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
- "Normal" version:
<lang AutoHotkey>MsgBox % reverse("asdf")
reverse(string) {
Loop, Parse, string reversed := A_LoopField . reversed Return reversed
}</lang>
- A ''much'' faster version:
<lang AHK>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
}</lang>
Applesoft BASIC
<lang ApplesoftBasic>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</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>
- Recursive
<lang awk>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")
}</lang>
- using split, then joining in front
<lang awk># Usage: awk -f reverse.awk -v s=Rosetta
function rev(s, i,a,r) {
split(s, a, "") for (i in a) r = a[i] r return r
} BEGIN {
if(!s) s = "Hello, world!" print s, "<-->", rev(s)
} </lang>
- Output:
Rosetta <--> attesoR
==[[:Category: | ]] [[Category: ]]</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(s)=concat(Vecrev(s))</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> alternative as procedure which changes the original <lang pascal>procedure revString(var s:string); var
i,j:integer; tmp:char;
begin
i := 1; j := length(s); while i<j do begin tmp:=s[i]; s[i]:=s[j]; s[j]:=tmp; inc(i); dec(j) end;
end;</lang>
Perl
This reverses characters (code points): <lang perl>$string = "visor"; $flip = reverse $string; # becomes "rosiv"</lang>
This reverses graphemes: <lang perl>$string = "Jose\x{301}"; # "José" in NFD $flip = join("", reverse $string =~ /\X/g); # becomes "ésoJ"</lang>
Perl 6
<lang perl6># Not transformative. my $reverse = flip $string;
- or
say "hello world".flip;</lang> Perl 6 is specced to work on graphemes by default, but current implementations are limited to processing codepoints.
PHP
<lang php>strrev($string);</lang>
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()
.
<lang php>// 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)));</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:
<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
<lang prolog>reverse("abcd", L), string_to_list(S,L).</lang>
- 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: <lang prolog>accRev([H|T], A, R) :- accRev(T, [H|A], R). accRev([], A, A).
rev(L,R) :- accRev(L,[],R).</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>
Qi
It's simplest just to use the common lisp REVERSE function. <lang Qi>(REVERSE "ABCD")</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="") )
}</lang>
Alternatively (using rev() function):
<lang R> revstring <- function(s) paste(rev(strsplit(s,"")1),collapse="")</lang>
<lang R>revstring("asdf") revstring("m\u00f8\u00f8se") Encoding("m\u00f8\u00f8se") # just to check if on your system it's something
# different!</lang>
- 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.
Rascal
<lang rascal>import String; reverse("string")</lang>
Racket
As in Scheme:
<lang Racket>#lang racket
(define (string-reverse s)
(list->string (reverse (string->list s))))
(string-reverse "aoeu")</lang>
- Output:
Welcome to DrRacket, version 5.3.3.5--2013-02-20(5eddac74/d) [3m]. Language: racket; memory limit: 512 MB. "ueoa" >
Raven
<lang Raven>"asdf" reverse</lang>
- Output:
fdsa
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
All methods shown below also work with NULL values.
using REVERSE bif
<lang rexx>/*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.*/</lang>
output
original string: A man, a plan, a canal, Panama! reversed string: !amanaP ,lanac a ,nalp a ,nam A
using SUBSTR bif, left to right
<lang rexx>/*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.*/</lang>
output is identical to the 1st version.
(Regarding the previous example) Another method of coding an abutment (an implied concatenation) is:
<lang rexx> string2 = substr(string1,j,1) || string2
/*───── or ─────*/ string2=substr(string1,j,1)||string2</lang>
using SUBSTR bif, right to left
<lang rexx>/*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.*/</lang>
output is identical to the 1st version.
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> or <lang ruby>#encoding: utf-8 "résumé niño".reverse #=> "oñin émusér"</lang>
Run BASIC
<lang runbasic>string$ = "123456789abcdefghijk" for i = len(string$) to 1 step -1
print mid$(string$,i,1);
next i</lang>
Rust
<lang rust>// rust 0.9 let s = "一二三四五六七八九十"; let reversed:~str = s.chars_rev().collect(); </lang> or <lang rust>let reversed:~str = "一二三四五六七八九十".chars_rev().collect(); </lang>
SAS
<lang sas>data _null_; length a b $11; a="I am Legend"; b=reverse(a); put a; put b; run;</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>
Slightly less easy way: <lang scala>"asdf".foldRight("")((a,b) => b+a)</lang>
Unicode-aware, method 1:
<lang scala>def reverse(s: String) = {
import java.text.{Normalizer,BreakIterator} val norm = Normalizer.normalize(s, Normalizer.Form.NFKC) // waffle -> waffle (optional) val it = BreakIterator.getCharacterInstance it setText norm def break(it: BreakIterator, prev: Int, result: List[String] = Nil): List[String] = it.next match { case BreakIterator.DONE => result case cur => break(it, cur, norm.substring(prev, cur) :: result) } break(it, it.first).mkString
}</lang>
- Output:
scala> reverse("as⃝df̅") res0: String = f̅ds⃝a
Unicode-aware, method 2: 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"
Scratch
Sed
<lang 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</lang>
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
Sidef
<lang ruby>"asdf".reverse; # fdsa "résumé niño".reverse; # oñin émusér</lang>
Slate
In-place reversal: <lang slate>'asdf' reverse</lang> Non-destructive reversal: <lang slate>'asdf' reversed</lang>
Smalltalk
<lang smalltalk>'asdf' reverse</lang>
the above does inplace, destructive reverse. It is usually better to use <lang smalltalk>'asdf' reversed</lang> which returns a new string.
SNOBOL4
ASCII-only <lang snobol> output = reverse(reverse("reverse")) end</lang>
- Output:
reverse
Standard ML
<lang sml>val str_reverse = implode o rev o explode; val string = "asdf"; val reversed = str_reverse string;</lang>
Swift
Swift's strings are iterated by Character
s, which represent "Unicode grapheme clusters", so reversing it reverses it with combining characters too:
<lang swift>func reverseString(s: String) -> String {
var result = "" result.extend(reverse(s)) return result
} println(reverseString("asdf")) println(reverseString("as⃝df̅"))</lang>
- Output:
fdsa f̅ds⃝a
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).
Turing
<lang 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 </lang>
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
UNIX Shell
<lang bash>
- !/bin/bash
str=abcde
for((i=${#str}-1;i>=0;i--)); do rev="$rev${str:$i:1}"; done
echo $rev </lang>
Unlambda
Reverse the whole input: <lang Unlambda>``@c`d``s`|k`@c</lang>
Ursala
<lang Ursala>#import std
- cast %s
example = ~&x 'asdf'
verbose_example = reverse 'asdf'</lang>
- Output:
'fdsa'
VBA
Non-recursive version
<lang VBA>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</lang>
Recursive version
<lang VBA>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</lang>
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
VBScript
<lang VBScript> WScript.Echo StrReverse("asdf") </lang>
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>
Visual Basic .NET
<lang vbnet> Function Reverse(ByVal s As String) As String
Dim t() as Char = s.toCharArray Array.reverse(t) Return new String(t) End Function</lang>
Wart
<lang wart>(rev "asdf")</lang>
Wart doesn't support unicode yet.
Wortel
<lang wortel>; the @rev operator reverses strings and arrays @rev "abc" ; returns "cba"
- or the same thing using a pointer expression
!~r "abc"</lang>
XPL0
<lang 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);
]</lang>
Output:
a ba cba .ablE was I ere I saw elbA
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>
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.
- Programming Tasks
- String manipulation
- 0815
- ACL2
- ActionScript
- Ada
- Agda2
- Aime
- ALGOL 68
- APL
- AppleScript
- AutoHotkey
- Applesoft BASIC
- AutoIt
- AWK
- PARI/GP
- Pascal
- Perl
- Perl 6
- PHP
- PicoLisp
- PL/I
- Pop11
- PostScript
- PowerShell
- Prolog
- Protium
- PureBasic
- Python
- Qi
- R
- Rascal
- Racket
- Raven
- REBOL
- Retro
- REXX
- RLaB
- Ruby
- Run BASIC
- Rust
- SAS
- Sather
- Scala
- Scheme
- Scratch
- Sed
- Seed7
- Sidef
- Slate
- Smalltalk
- SNOBOL4
- Standard ML
- Swift
- Tcl
- TI-83 BASIC
- Turing
- TUSCRIPT
- UNIX Shell
- Unlambda
- Ursala
- VBA
- VBScript
- Vedit macro language
- Visual Basic .NET
- Wart
- Wortel
- XPL0
- Yorick
- Zkl
- Bc/Omit
- Dc/Omit
- Openscad/Omit