Reverse a string: Difference between revisions

m
→‎{{header|Oberon}}: Fixed language name
(Add CLU)
m (→‎{{header|Oberon}}: Fixed language name)
(61 intermediate revisions by 33 users not shown)
Line 17:
=={{header|0815}}==
This program reverses each line of its input.
<langsyntaxhighlight lang="0815">}:r: Start reader loop.
!~>& Push a character to the "stack".
<:a:=- Stop reading on newline.
Line 26:
${~ Print the current character until it's 0.
^:p:
#:r: Read again.</langsyntaxhighlight>
 
{{out}}
 
<langsyntaxhighlight lang="bash">echo -e "foo\nbar" | 0815 rev.0
oof
rab</langsyntaxhighlight>
 
=={{header|11l}}==
<syntaxhighlight lang ="11l">reversed(string)</langsyntaxhighlight>
 
=={{header|360 Assembly}}==
For maximum compatibility, this program uses only the basic instruction set (S/360)
and an ASSIST macro (XPRNT) to keep the code as short as possible.
<langsyntaxhighlight lang="360asm">* Reverse a string 21/05/2016
REVERSE CSECT
USING REVERSE,R13 base register
Line 69:
TMP DS CL12
REGEQU
END REVERSE</langsyntaxhighlight>
{{out}}
<pre>
Line 75:
</pre>
This second example uses MVCIN introduced in S/370 architecture.
<langsyntaxhighlight lang="360asm">* Reverse a string 25/04/2020
REVERSEI CSECT
USING REVERSEI,R13 base register
Line 93:
BB DS CL(L'AA) b
REGEQU
END REVERSEI</langsyntaxhighlight>
{{out}}
<pre>
Line 121:
 
 
<langsyntaxhighlight lang="8080asm"> org 100h
jmp test
 
Line 194:
pop h
inx h
jmp loop</langsyntaxhighlight>
 
=={{header|8th}}==
In 8th strings are UTF-8 and the language retains characters per-se:
<langsyntaxhighlight lang="forth">
"abc" s:rev
</syntaxhighlight>
</lang>
{{out}}
<tt>"cba"</tt>
 
=={{header|ACL2}}==
<langsyntaxhighlight Lisplang="lisp">(reverse "hello")</langsyntaxhighlight>
 
ACL2 does not support unicode.
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">PROC Reverse(CHAR ARRAY src,dst)
BYTE i,j
 
Line 232:
Test("123456789")
Test("!noitcA iratA")
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Reverse_a_string.png Screenshot from Atari 8-bit computer]
Line 242:
 
=={{header|ActionScript}}==
<langsyntaxhighlight ActionScriptlang="actionscript">function reverseString(string:String):String
{
var reversed:String = new String();
Line 253:
{
return string.split('').reverse().join('');
}</langsyntaxhighlight>
 
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO;
procedure Reverse_String is
Line 269:
begin
Put_Line (Reverse_It (Get_Line));
end Reverse_String;</langsyntaxhighlight>
 
=={{header|Agda}}==
Using the Agda standard library, version 01.67 .
<syntaxhighlight lang="agda">
<lang agda2>module reverse_string where
module ReverseString where
 
open import Data.String using (String ; fromList ; toList)
open import Data.List using (reverse)
 
reverse_stringreverse-string : String → String
reverse_stringreverse-string s = fromList (reverse (toList s))</lang>
</syntaxhighlight>
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">o_(b_reverse("Hello, World!"), "\n");</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
Line 288 ⟶ 290:
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386}}
<langsyntaxhighlight lang="algol68">PROC reverse = (REF STRING s)VOID:
FOR i TO UPB s OVER 2 DO
CHAR c = s[i];
Line 300 ⟶ 302:
reverse(text);
print((text, new line))
)</langsyntaxhighlight>
{{out}}
<pre>
Line 307 ⟶ 309:
 
=={{header|Amazing Hopper}}==
<syntaxhighlight lang="amazing hopper">
<lang Amazing Hopper>
#include <hopper.h>
 
Line 314 ⟶ 316:
reverse(s),strtoutf8, println
{0}return
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 320 ⟶ 322:
</pre>
=={{header|Apex}}==
<langsyntaxhighlight lang="java">
String str = 'Hello World!';
str = str.reverse();
system.debug(str);
</syntaxhighlight>
</lang>
 
=={{header|APL}}==
<langsyntaxhighlight lang="apl"> ⌽'asdf'
fdsa</langsyntaxhighlight>
 
=={{header|AppleScript}}==
{{works with |AppleScript| 2.0 or newer.}}
<langsyntaxhighlight AppleScriptlang="applescript">reverseString("Hello World!")
 
on reverseString(str)
reverse of characters of str as string
end reverseString</langsyntaxhighlight>
 
'''NB.''' Since coercing lists to string involves the interpolation of the current value of AppleScript's text item delimiters between the list items, it's considered best practice to set the delimiters ''explicitly'' to their default value of <code>{""}</code> (or just <code>""</code>) before doing an operation like this, in case they've been set to something else elsewhere in the script:
 
<langsyntaxhighlight lang="applescript">reverseString("Hello World!")
 
on reverseString(str)
Line 348 ⟶ 350:
set AppleScript's text item delimiters to astid
return reversedString
end reverseString</langsyntaxhighlight>
----
Or, if we want a polymorphic '''reverse()''' for both strings and lists, we can define it either in terms of a generic fold/reduce, or using the built-in method for lists:
 
<langsyntaxhighlight AppleScriptlang="applescript">-- Using either a generic foldr(f, a, xs)
 
-- reverse1 :: [a] -> [a]
Line 429 ⟶ 431:
end script
end if
end mReturn</langsyntaxhighlight>
 
{{Out}}
<langsyntaxhighlight AppleScriptlang="applescript">{{"! ereht olleH", {5, 4, 3, 2, 1}},
{"! ereht olleH", {5, 4, 3, 2, 1}}}</langsyntaxhighlight>
 
=={{header|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>
 
=={{header|Arturo}}==
<langsyntaxhighlight lang="rebol">str: "Hello World"
 
print reverse str</langsyntaxhighlight>
 
{{out}}
Line 459 ⟶ 448:
=={{header|AutoHotkey}}==
; <nowiki>"Normal" version:</nowiki>
<langsyntaxhighlight AutoHotkeylang="autohotkey">MsgBox % reverse("asdf")
 
reverse(string)
Line 466 ⟶ 455:
reversed := A_LoopField . reversed
Return reversed
}</langsyntaxhighlight>
; <nowiki>A ''much'' slower version:</nowiki>
<langsyntaxhighlight AHKlang="ahk">Reverse(String){ ; credit to Rseding91
If (A_IsUnicode){
SLen := StrLen(String) * 2
Line 486 ⟶ 475:
Return RString
}</langsyntaxhighlight>
 
=={{header|AutoIt}}==
<langsyntaxhighlight AutoItlang="autoit">#AutoIt Version: 3.2.10.0
$mystring="asdf"
$reverse_string = ""
Line 500 ⟶ 489:
Next
 
MsgBox(0, "Reversed string is:", $reverse_string)</langsyntaxhighlight>
 
=={{header|Avail}}==
<langsyntaxhighlight Availlang="avail">"asfd" reversed</langsyntaxhighlight>
 
=={{header|AWK}}==
<langsyntaxhighlight lang="awk">function reverse(s)
{
p = ""
Line 515 ⟶ 504:
BEGIN {
print reverse("edoCattesoR")
}</langsyntaxhighlight>
 
;Recursive
<langsyntaxhighlight lang="awk">function reverse(s ,l)
{
l = length(s)
Line 526 ⟶ 515:
BEGIN {
print reverse("edoCattesoR")
}</langsyntaxhighlight>
 
;using split, then joining in front:
<langsyntaxhighlight lang="awk"># Usage: awk -f reverse.awk -v s=Rosetta
 
function rev(s, i,len,a,r) {
Line 541 ⟶ 530:
print s, "<-->", rev(s)
}
</syntaxhighlight>
</lang>
{{out}}
Rosetta <--> attesoR
Line 547 ⟶ 536:
=={{header|Babel}}==
This example will handle UTF-8 encoded Unicode but doesn't handle combining characters.
<langsyntaxhighlight lang="babel">strrev: { str2ar ar2ls reverse ls2lf ar2str }</langsyntaxhighlight>
*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
Line 555 ⟶ 544:
 
=={{header|BaCon}}==
<langsyntaxhighlight lang="freebasic">OPTION UTF8 TRUE
s$ = "asdf"
PRINT REVERSE$(s$)</langsyntaxhighlight>
 
Unicode preservation works in BaCon 3.6 and higher.
 
=={{header|BASIC}}==
 
{{works with|QuickBasic|4.5}}
==={{header|Applesoft BASIC}}===
<lang qbasic>function reverse$(a$)
<syntaxhighlight lang="applesoftbasic">10 A$ = "THE FIVE BOXING WIZARDS JUMP QUICKLY"
b$ = ""
20 GOSUB 100REVERSE
for i = 1 to len(a$)
30 PRINT R$
b$ = mid$(a$, i, 1) + b$
40 END
next i
 
reverse$ = b$
100 REMREVERSE A$
end function</lang>
110 R$ = ""
120 FOR I = 1 TO LEN(A$)
130 R$ = MID$(A$, I, 1) + R$
140 NEXT I
150 RETURN</syntaxhighlight>
 
==={{header|BASIC256}}===
<syntaxhighlight lang="vb">s = "asdf"
print "'"; s; "' reversed is '"; reverse(s); "'"
end
 
function reverse(a)
b = ""
for i = 1 to length(a)
b = mid(a, i, 1) + b
next i
return b
end function</syntaxhighlight>
{{out}}
<pre>'asdf' reversed is 'fdsa'</pre>
 
==={{header|Commodore BASIC}}===
{{works with|Commodore BASIC|3.5,7.0}}
Commodore BASIC 3.5 turned MID$ into an lvalue function, and assigning a string of the same length to MID$ replaces the characters instead of allocating a new string, so the reversal can be done in-place:
 
<syntaxhighlight lang="basic">
100 INPUT "STRING";S$
110 FOR I=1 TO INT(LEN(S$)/2)
120 : J=LEN(S$)+1-I
130 : T$=MID$(S$,I,1)
140 : MID$(S$,I,1) = MID$(S$,J,1)
150 : MID$(S$,J,1) = T$
160 NEXT I
170 PRINT S$</syntaxhighlight>
{{Out}}
<pre>STRING? THIS IS A TEST
TSET A SI SIHT
 
READY.</pre>
 
==={{header|IS-BASIC}}===
<langsyntaxhighlight ISlang="is-BASICbasic">100 INPUT PROMPT "String: ":TX$
120 LET REV$=""
130 FOR I=LEN(TX$) TO 1 STEP-1
140 LET REV$=REV$&TX$(I)
150 NEXT
160 PRINT REV$</langsyntaxhighlight>
 
==={{header|QuickBASIC}}===
{{works with|QBasic|1.1}}
{{works with|QuickBasic|4.5}}
<syntaxhighlight lang="qbasic">function reverse$(a$)
b$ = ""
for i = 1 to len(a$)
b$ = mid$(a$, i, 1) + b$
next i
reverse$ = b$
end function</syntaxhighlight>
 
==={{header|Sinclair ZX81 BASIC}}===
<langsyntaxhighlight lang="basic">10 INPUT S$
20 LET T$=""
30 FOR I=LEN S$ TO 1 STEP -1
40 LET T$=T$+S$(I)
50 NEXT I
60 PRINT T$</langsyntaxhighlight>
 
==={{header|True BASIC}}===
<syntaxhighlight lang="qbasic">FUNCTION reverse$(a$)
LET b$ = ""
FOR i = 1 TO LEN(a$)
LET b$ = (a$)[i:i+1-1] & b$
NEXT i
LET reverse$ = b$
END FUNCTION
 
LET s$ = "asdf"
PRINT "'"; s$; "' reversed is '"; reverse$(s$); "'"
END</syntaxhighlight>
{{out}}
<pre>'asdf' reversed is 'fdsa'</pre>
 
==={{header|XBasic}}===
{{works with|Windows XBasic}}
<syntaxhighlight lang="qbasic">PROGRAM "progname"
VERSION "0.0000"
 
DECLARE FUNCTION Entry ()
DECLARE FUNCTION reverse$ (a$)
 
FUNCTION Entry ()
s$ = "asdf"
PRINT "'"; s$; "' reversed is '"; reverse$(s$); "'"
END FUNCTION
 
FUNCTION reverse$ (a$)
b$ = ""
FOR i = 1 TO LEN(a$)
b$ = MID$(a$, i, 1) + b$
NEXT i
RETURN b$
END FUNCTION
END PROGRAM</syntaxhighlight>
{{out}}
<pre>'asdf' reversed is 'fdsa'</pre>
 
==={{header|Yabasic}}===
<syntaxhighlight lang="vb">s$ = "asdf"
print "'", s$, "' reversed is '", reverse$(s$), "'"
end
 
sub reverse$(a$)
b$ = ""
for i = 1 to len(a$)
b$ = mid$(a$, i, 1) + b$
next i
return b$
end sub</syntaxhighlight>
{{out}}
<pre>'asdf' reversed is 'fdsa'</pre>
 
=={{header|Batch File}}==
<langsyntaxhighlight lang="dos">@echo off
setlocal enabledelayedexpansion
call :reverse %1 res
Line 604 ⟶ 697:
set str=%str:~1%
set %2=%chr%!%2!
goto loop</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic"> PRINT FNreverse("The five boxing wizards jump quickly")
END
Line 615 ⟶ 708:
B$ += MID$(A$,C%,1)
NEXT
= B$</langsyntaxhighlight>
 
=={{header|Beef}}==
Beef does not have a built-in Reverse method for strings, however one can 'extend' the builtin String class to provide a Reverse function.
<syntaxhighlight lang="csharp">using System;
 
namespace System
{
extension String
{
public void Reverse()
{
int i = 0;
int j = mLength - 1;
while (i < j)
{
Swap!(Ptr[i++], Ptr[j--]);
}
}
}
}
 
namespace StringReverse
{
class Program
{
static void Main()
{
String s = scope .("abcdef");
s.Reverse();
Console.WriteLine(s);
}
}
}
</syntaxhighlight>
 
=={{header|Befunge}}==
Reads a line from stdin and write the reverse to stdout. Can be made to repeat indefinitely by removing the final <tt>@</tt> command.
 
<langsyntaxhighlight lang="befunge">55+~>:48>*#8\#4`#:!#<#~_$>:#,_@</langsyntaxhighlight>
 
=={{header|Binary Lambda Calculus}}==
 
This 9 byte program, featured on https://www.ioccc.org/2012/tromp/hint.html, reverses its input in byte-oriented BLC:
 
<pre>16 46 80 17 3e f0 b7 b0 40</pre>
 
=={{header|BQN}}==
BQN has a reverse builtin, given as <code>⌽</code>.
 
<syntaxhighlight lang="bqn"> ⌽"racecar"
"racecar"</syntaxhighlight>
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat"> ( reverse
= L x
. :?L
Line 637 ⟶ 776:
| str$!L
)
& out$reverse$Ελληνικά</langsyntaxhighlight>
{{out}}
<pre>άκινηλλΕ</pre>
 
=={{header|Brainf***}}==
<langsyntaxhighlight lang="bf">[-]>,[>,]<[.<]</langsyntaxhighlight>
Another solution:
<langsyntaxhighlight 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
+++++ +++++ +++ . --- .</langsyntaxhighlight>
 
=={{header|Brat}}==
<langsyntaxhighlight lang="brat">p "olleh".reverse #Prints "hello"</langsyntaxhighlight>
 
=={{header|Burlesque}}==
 
<langsyntaxhighlight lang="burlesque">
"Hello, world!"<-
</syntaxhighlight>
</lang>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
Line 726 ⟶ 865:
printf("%s => %s\n", su, mb_reverse(su));
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>abcdef => fedcba
Line 732 ⟶ 871:
 
{{libheader|GLib}}
<langsyntaxhighlight lang="c">#include <glib.h>
gchar *srev (const gchar *s) {
if (g_utf8_validate(s,-1,NULL)) {
Line 744 ⟶ 883:
printf ("%s\n",srev(u));
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp}}==
C# does not have a built-in Reverse method for strings, and cannot reverse them in place because they 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:
<langsyntaxhighlight lang="csharp">static string ReverseString(string input)
{
char[] inputChars = input.ToCharArray();
Array.Reverse(inputChars);
return new string(inputChars);
}</langsyntaxhighlight>
 
As of .Net 3.5 the LINQ-to-objects allows the Reverse() extension method to be called 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 the constructor of string that accepts a char array:
<langsyntaxhighlight lang="csharp">using System.Linq;
 
// ...
Line 762 ⟶ 901:
return new string(input.Reverse().ToArray());
 
// ...</langsyntaxhighlight>
 
'''Version supporting combining characters:'''
 
System.Globalization.StringInfo provides a means of separating a string into individual graphemes.
<langsyntaxhighlight lang="csharp">public string ReverseElements(string s)
{
// In .NET, a text element is series of code units that is displayed as one character, and so reversing the text
Line 780 ⟶ 919:
while (enumerator.MoveNext())
yield return enumerator.Current;
}</langsyntaxhighlight>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <iostreamstring>
#include <stringiostream>
#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'\n';
}</syntaxhighlight>
return 0;
}</lang>
 
=={{header|Caché ObjectScript}}==
Line 803 ⟶ 940:
 
=={{header|Ceylon}}==
<syntaxhighlight lang="ceylon">
<lang Ceylon>
shared void run() {
 
Line 817 ⟶ 954:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Clipper}}==
Works with versions since 5, because ''LOCAL'' variables and the ''+='' operator was not implemented before.
<langsyntaxhighlight Clipperlang="clipper">FUNCTION Reverse(sIn)
LOCAL sOut := "", i
FOR i := Len(sIn) TO 1 STEP -1
sOut += Substr(sIn, i, 1)
NEXT
RETURN sOut</langsyntaxhighlight>
 
=={{header|Clojure}}==
Line 832 ⟶ 969:
=== A Simple implementation with the magic of "conj" function ===
 
<langsyntaxhighlight lang="lisp">
(defn reverse-string [s]
"Returns a string with all characters in reverse"
(apply str (reduce conj '() s)))
</syntaxhighlight>
</lang>
 
=== Other alternatives (resorting to the "reverse" function in the standard library)===
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.
a) <langsyntaxhighlight lang="lisp">(defn str-reverse [s] (apply str (reverse s)))</langsyntaxhighlight>
 
b) <langsyntaxhighlight lang="lisp">(apply str (interpose " " (reverse (.split "the quick brown fox" " "))))</langsyntaxhighlight>
 
=== 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.
<langsyntaxhighlight lang="lisp">(defn combining? [c]
(let [type (Character/getType c)]
;; currently hardcoded to the types taken from the sample string
Line 866 ⟶ 1,003:
"Unicode-safe string reverse"
[s]
(apply str (apply concat (reverse (group s)))))</langsyntaxhighlight>
{{out}}
<pre>
Line 879 ⟶ 1,016:
 
=={{header|CLU}}==
<langsyntaxhighlight lang="clu">reverse = proc (s: string) returns (string)
rslt: array[char] := array[char]$predict(1,string$size(s))
for c: char in string$chars(s) do
Line 890 ⟶ 1,027:
po: stream := stream$primary_output()
stream$putl(po, reverse("!dlrow ,olleH"))
end start_up</langsyntaxhighlight>
{{out}}
<pre>Hello, world!</pre>
 
=={{header|COBOL}}==
<syntaxhighlight lang ="cobol">FUNCTION REVERSE('QWERTY')</langsyntaxhighlight>
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="javascript">"qwerty".split("").reverse().join ""</langsyntaxhighlight>
 
=={{header|ColdFusion}}==
You can reverse anything that can be written to the document in hashmarks (i.e. strings, numbers, now( ), etc.).
<langsyntaxhighlight lang="cfm"><cfset myString = "asdf" />
<cfset myString = reverse( myString ) /></langsyntaxhighlight>
 
=={{header|Common Lisp}}==
<syntaxhighlight lang ="lisp">(reverse my-string)</langsyntaxhighlight>
 
=={{header|Component Pascal}}==
BlackBox Component Builder
<langsyntaxhighlight lang="oberon2">
MODULE BbtReverseString;
IMPORT StdLog;
Line 937 ⟶ 1,074:
END Do;
END BbtReverseString.
</syntaxhighlight>
</lang>
Execute: ^Q BbtReverseString.Do<br/>
{{Out}}
Line 945 ⟶ 1,082:
 
=={{header|Cowgol}}==
<langsyntaxhighlight lang="cowgol">include "cowgol.coh";
include "strings.coh";
 
Line 969 ⟶ 1,106:
var str: [uint8] := "\nesreveR";
CopyString(str, &buf[0]);
print(StrRev(&buf[0]));</langsyntaxhighlight>
 
{{out}}
Line 976 ⟶ 1,113:
 
=={{header|Crystal}}==
<langsyntaxhighlight lang="ruby"># version 0.21.1
 
strings = ["asdf", "as⃝df̅"]
strings.each do |s|
puts "#{s} -> #{s.reverse}"
end</langsyntaxhighlight>
 
{{out}}
Line 990 ⟶ 1,127:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">void main() {
import std.range, std.conv;
 
Line 1,005 ⟶ 1,142:
dstring s4 = "hello"d;
assert(s4.dup.reverse == "olleh"d); // simple but inefficient (copies first, then reverses)
}</langsyntaxhighlight>
 
=={{header|Dart}}==
Since Dart strings are sequences of [http://en.wikipedia.org/wiki/UTF-16 UTF-16] code units, it would not be sufficient to simply reverse the characters in strings, as this would not work with UTF-16 [http://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B10000_to_U.2B10FFFF surrogate pairs] (pairs of UTF-16 code units that represent single characters [http://en.wikipedia.org/wiki/Plane_(Unicode)#Supplementary_Multilingual_Plane 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:
 
<langsyntaxhighlight lang="dart">String reverse(String s) => new String.fromCharCodes(s.runes.toList().reversed);</langsyntaxhighlight>
 
A more complete example with unit tests would look like this:
 
<langsyntaxhighlight lang="dart">import 'package:unittest/unittest.dart';
 
String reverse(String s) => new String.fromCharCodes(s.runes.toList().reversed);
Line 1,030 ⟶ 1,167:
});
});
}</langsyntaxhighlight>
 
 
=={{header|DBL}}==
<syntaxhighlight lang="dbl">K=
<lang DBL>K=
STR_OUT=
FOR J=%TRIM(STR_IN) STEP -1 UNTIL 1
Line 1,041 ⟶ 1,178:
STR_OUT(K:1)=STR_IN(J:1)
END
</syntaxhighlight>
</lang>
 
 
Line 1,047 ⟶ 1,184:
Reversing "Hello world!" which is "22405534230753963835153736737" in Dc's numerical string representaion.<br>
Due to using "~" this example needs GNU Dc or OpenBSD Dc.
<langsyntaxhighlight lang="dc">22405534230753963835153736737 [ 256 ~ d SS 0<F LS SR 1+ ] d sF x 1 - [ 1 - d 0<F 256 * LR + ] d sF x P</langsyntaxhighlight>
<pre>
!dlrow olleH
Line 1,053 ⟶ 1,190:
 
=={{header|Delphi}}==
<langsyntaxhighlight Delphilang="delphi">function ReverseString(const InString: string): string;
var
i: integer;
Line 1,059 ⟶ 1,196:
for i := Length(InString) downto 1 do
Result := Result + InString[i];
end;</langsyntaxhighlight>
You could also use this RTL function Introduced in Delphi 6:
<syntaxhighlight lang Delphi="delphi">StrUtils.ReverseString</langsyntaxhighlight>
 
Another alternative.
<syntaxhighlight lang="delphi">
<lang Delphi>
function Reverse(const s: string): string;
var
Line 1,080 ⟶ 1,217:
result[aLength - i + 1] := c;
end;
end;</langsyntaxhighlight>
All versions has the same perfomance, then StrUtils is recomended.
 
=={{header|Draco}}==
<syntaxhighlight lang="draco">/* Reverse string in place */
proc nonrec reverse(*char s) void:
*char e;
char t;
e := s;
while e* /= '\e' do
e := e + 1
od;
while
e := e - 1;
s < e
do
t := e*;
e* := s*;
s* := t;
s := s + 1
od
corp
 
proc nonrec main() void:
*char testString = "!dlrow ,olleH";
reverse(testString);
writeln(testString)
corp</syntaxhighlight>
{{out}}
<pre>Hello, world!</pre>
 
=={{header|dt}}==
<syntaxhighlight lang="dt">"asdf" rev</syntaxhighlight>
 
=={{header|DWScript}}==
Line 1,088 ⟶ 1,256:
=={{header|Dyalect}}==
 
<langsyntaxhighlight lang="dyalect">let str = "asdf"
func String.reverseReverse() {
var cs = []
let len = this.lenLength()
for n in 1..len {
cs.addAdd(this[len - n])
}
String(values: cs)
}
str.reverseReverse()</langsyntaxhighlight>
 
=={{header|Déjà Vu}}==
<langsyntaxhighlight lang="dejavu">!print concat chars "Hello"</langsyntaxhighlight>
{{out}}
<pre>olleH</pre>
 
=={{header|EasyLang}}==
 
<syntaxhighlight lang="easylang">
func$ reverse s$ .
a$[] = strchars s$
for i = 1 to len a$[] div 2
swap a$[i] a$[len a$[] - i + 1]
.
return strjoin a$[]
.
print reverse "hello"
</syntaxhighlight>
 
=={{header|E}}==
[[Category:E examples needing attention]] <!-- Replacing accum, grapheme clusters -->
<langsyntaxhighlight lang="e">pragma.enable("accumulator")
def reverse(string) {
return accum "" for i in (0..!(string.size())).descending() { _ + string[i] }
}</langsyntaxhighlight>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="lisp">
(define (string-reverse string)
(list->string (reverse (string->list string))))
Line 1,122 ⟶ 1,303:
(string-reverse "un roc lamina l animal cornu")
→ unroc lamina l animal cor nu
</syntaxhighlight>
</lang>
 
=={{header|EGL}}==
<langsyntaxhighlight EGLlang="egl">function reverse( str string ) returns( string )
result string;
for ( i int from StrLib.characterLen( str ) to 1 decrement by 1 )
Line 1,131 ⟶ 1,312:
end
return( result );
end</langsyntaxhighlight>
 
=={{header|Eiffel}}==
<langsyntaxhighlight lang="eiffel">class
APPLICATION
create
Line 1,148 ⟶ 1,329:
my_string: STRING
-- Used for reversal
end</langsyntaxhighlight>
{{out}}
<pre>
Line 1,155 ⟶ 1,336:
 
=={{header|Ela}}==
<langsyntaxhighlight lang="ela">reverse_string str = rev len str
where len = length str
rev 0 str = ""
Line 1,161 ⟶ 1,342:
where nn = n - 1
 
reverse_string "Hello"</langsyntaxhighlight>
 
{{out}}<pre>"olleH"</pre>
Line 1,167 ⟶ 1,348:
Another approach is to covert a string to a list, reverse a list and then convert it back to a string:
 
<langsyntaxhighlight lang="ela">open string
fromList <| reverse <| toList "Hello" ::: String</langsyntaxhighlight>
 
=={{header|Elena}}==
ELENA 4.x:
<langsyntaxhighlight lang="elena">import system'routines;
import extensions;
import extensions'text;
Line 1,185 ⟶ 1,366:
{
console.printLine("Hello World".reversedLiteral())
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,193 ⟶ 1,374:
=={{header|Elixir}}==
Elixir handles Unicode graphemes correctly by default.
<langsyntaxhighlight lang="elixir">
IO.puts (String.reverse "asdf")
IO.puts (String.reverse "as⃝df̅")
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 1,204 ⟶ 1,385:
 
=={{header|Elm}}==
<syntaxhighlight lang="elm">module Main exposing (main)
<lang elm>-- The import on the next line provides the reverse string
-- functionality satisfying the rosettacode.org task description.
import String exposing (reverse)
 
import Html exposing (Html, text, div, p)
-- The rest is fairly boilerplate code demonstrating
import Html.Attributes exposing (style)
-- interactively that the reverse function works.
import Html exposing (Html, Attribute, text, div, input)
import Html.Attributes exposing (placeholder, value, style)
import Html.Events exposing (on, targetValue)
import Html.App exposing (beginnerProgram)
 
main = beginnerProgram { model = "", view = view, update = update }
 
change myText =
update newStr oldStr = newStr
text ("reverse " ++ myText
++ " = " ++ String.reverse myText)
 
view : String -> Html String
view forward =
div []
([ input
[ placeholder "Enter a string to be reversed."
, value forward
, on "input" targetValue
, myStyle
]
[]
] ++
[ let backward = reverse forward
in div [ myStyle] [text backward]
])
 
main =
myStyle : Attribute msg
div [style "margin" "5%", style "font-size" "1.5em"]
myStyle =
[change "as⃝da"
style
, p [] ("width",[change "100%a⃝su-as⃝u")]
, ("height",p [] [change "20pxHello!")]
]
, ("padding", "5px 0 0 5px")
</syntaxhighlight>
, ("font-size", "1em")
, ("text-align", "left")
]</lang>
 
Link to live demo: httphttps://dc25ellie-app.github.io/reverseStringElmcom/qdg6RP3DGCBa1
{{out}}
<pre>
reverse as⃝da = ad⃝sa
reverse a⃝su-as⃝u = u⃝sa-us⃝a
reverse Hello! = !olleH
</pre>
 
=={{header|Emacs Lisp}}==
<langsyntaxhighlight lang="lisp">(reverse "Hello World")</langsyntaxhighlight>
{{out}}
<pre>
Line 1,254 ⟶ 1,420:
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">1> lists:reverse("reverse!").
"!esrever"</langsyntaxhighlight>
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.
<langsyntaxhighlight lang="erlang">reverse(Bin) ->
Size = size(Bin)*8,
<<T:Size/integer-little>> = Bin,
<<T:Size/integer-big>>.</langsyntaxhighlight>
{{out}}
<pre>
Line 1,268 ⟶ 1,434:
 
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM REVERSE_STRING
 
Line 1,284 ⟶ 1,450:
PRINT(R$)
END PROGRAM
</syntaxhighlight>
</lang>
 
=={{header|Euler Math Toolbox}}==
 
<syntaxhighlight lang="euler math toolbox">
<lang Euler Math Toolbox>
>function strrev (s) := chartostr(fliplr(strtochar(s)))
>strrev("This is a test!")
!tset a si sihT
</syntaxhighlight>
</lang>
 
=={{header|Euphoria}}==
 
<langsyntaxhighlight lang="euphoria">
include std/sequence.e
printf(1, "%s\n", {reverse("abcdef") })
</syntaxhighlight>
</lang>
 
=={{header|Explore}}==
Line 1,307 ⟶ 1,473:
 
=={{header|Ezhil}}==
<syntaxhighlight lang="ezhil">
<lang Ezhil>
 
## இந்த நிரல் தரப்படும் சரம் ஒன்றைத் தலைகீழாகத் திருப்பி அச்சிடும்
Line 1,354 ⟶ 1,520:
பதிப்பி "வேறொரு வகையில் திருப்பியுள்ளோம்: " மீண்டும்திருப்புக(அ)
 
</syntaxhighlight>
</lang>
 
=={{header|F_Sharp|F#}}==
===The function===
<langsyntaxhighlight lang="fsharp">
// Reverse a string. Nigel Galloway: August 14th., 2019
let strRev α=let N=System.Globalization.StringInfo.GetTextElementEnumerator(α)
List.unfold(fun n->if n then Some(N.GetTextElement(),N.MoveNext()) else None)(N.MoveNext())|>List.rev|>String.concat ""
</syntaxhighlight>
</lang>
===The Task===
I was a little concerned when entering this task because in the edit window the overline appears above the d, but when previewed it is correctly above the f, using Firefox anyway. Using XTERM the output is correct with the s inside a circle but appears as sO in Firefox.
<langsyntaxhighlight lang="fsharp">
printfn "%s" (strRev "as⃝df̅")
printfn "%s" (strRev "Nigel")
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,377 ⟶ 1,543:
=={{header|Factor}}==
A string is a sequence and there is a default reverse implementation for those.
<langsyntaxhighlight lang="factor">"hello" reverse</langsyntaxhighlight>
<code>string-reverse</code> preserves graphemes:
<langsyntaxhighlight lang="factor">"as⃝df̅" string-reverse "f̅ds⃝a" = .</langsyntaxhighlight>
 
=={{header|FALSE}}==
This solution does not take into account combination characters:
<langsyntaxhighlight lang="false">1_
[^$1_=~][]#%
[$1_=~][,]#</langsyntaxhighlight>
This solution does take into account combination characters (except for half-marks):
<langsyntaxhighlight lang="false">1_
[^$1_=~][
$$767>\879\>&
Line 1,394 ⟶ 1,560:
[\]?
]#%
[$1_=~][,]#</langsyntaxhighlight>
 
=={{header|Fancy}}==
<langsyntaxhighlight lang="fancy">"hello world!" reverse</langsyntaxhighlight>
 
=={{header|FBSL}}==
A slow way
<langsyntaxhighlight lang="qbasic">Function StrRev1(ByVal $p1)
dim $b = ""
REPEAT len(p1)
Line 1,409 ⟶ 1,575:
return b
End Function
</syntaxhighlight>
</lang>
 
A much faster (twice at least) way
<langsyntaxhighlight lang="qbasic">Function StrRev2(ByVal $p1)
dim $b = "", %i
for i = len(p1) DOWNTO 1
Line 1,418 ⟶ 1,584:
next
return b
End Function</langsyntaxhighlight>
 
An even faster way using PEEK, POKE, double-calls and quantity-in-hand
<langsyntaxhighlight lang="qbasic">Function StrRev3( $s )
FOR DIM x = 1 TO LEN(s) \ 2
PEEK(@s + LEN - x, $1)
Line 1,428 ⟶ 1,594:
RETURN s
end function
</syntaxhighlight>
</lang>
 
An even faster way using the DynC (Dynamic C) mode
<langsyntaxhighlight lang="c">DynC StringRev($theString) As String
void rev(char *str)
{
Line 1,450 ⟶ 1,616:
return theString;
}
End DynC</langsyntaxhighlight>
 
Using DynASM, the Dynamic Assembler mode.
<langsyntaxhighlight lang="asm">DYNASM RevStr(BYVAL s AS STRING) AS STRING
// get length of string
// divide by two
Line 1,502 ⟶ 1,668:
RET
END DYNASM
</syntaxhighlight>
</lang>
 
=={{header|Fe}}==
In this language, strings are very limited and are not designed to store large text data, so there are no built-in operations to work with strings. But with the C API you can make functions that convert a string to a list and vice versa.
<syntaxhighlight lang="c">
#define MAXSTRINGLEN ( 1024 )
 
/* chop string to list of single character strings */
static fe_Object* chop(fe_Context *ctx, fe_Object *args) {
char buf[MAXSTRINGLEN];
int len = fe_tostring(ctx, fe_nextarg(ctx, &args), buf, sizeof(buf));
int gc = fe_savegc(ctx);
args = fe_bool(ctx, 0);
while (len > 0) {
buf[len--] = '\0';
args = fe_cons(ctx, fe_string(ctx, buf + len), args);
fe_restoregc(ctx, gc);
fe_pushgc(ctx, args);
}
return args;
}
 
/* pack list of strings to single string */
static fe_Object* pack(fe_Context *ctx, fe_Object *args) {
char buf[MAXSTRINGLEN], *ptr = buf;
for (args = fe_nextarg(ctx, &args); !fe_isnil(ctx, args);) {
ptr += fe_tostring(ctx, fe_nextarg(ctx, &args), ptr, buf + sizeof(buf) - ptr);
}
return fe_string(ctx, buf);
}
</syntaxhighlight>
So, we can manipulate strings like lists:
<syntaxhighlight lang="clojure">
; reverse list
(= reverse (fn (lst)
(let res nil)
(while lst
(= res (cons (car lst) res))
(= lst (cdr lst)))
res))
 
; chop string to list, reverse list and pack it back to string
(print (pack (reverse (chop "Hello world!"))))
</syntaxhighlight>
Output:
<syntaxhighlight lang="clojure">
!dlrow olleH
</syntaxhighlight>
 
=={{header|Fennel}}==
Uses the same methods (and suffers from the same limitations) as [[#Lua|the Lua example]].
<syntaxhighlight lang="fennel">
(let [example :asdf]
(string.reverse example) ; fdsa
(example:reverse) ; fdsa
nil)
</syntaxhighlight>
 
=={{header|Forth}}==
 
=== Method 1 ===
<langsyntaxhighlight lang="forth">: exchange ( a1 a2 -- )
2dup c@ swap c@ rot c! swap c! ;
: reverse ( c-addr u -- )
Line 1,515 ⟶ 1,737:
repeat 2drop ;
 
s" testing" 2dup reverse type \ gnitset</langsyntaxhighlight>
 
=== Method 2 Using the stack ===
<langsyntaxhighlight lang="forth">\ reverse a string using the data stack for temporary storage
 
: mystring ( -- caddr len) S" ABCDEFGHIJKLMNOPQRSTUVWXYZ987654321" ;
Line 1,524 ⟶ 1,746:
: pushstr ( caddr len -- c..c[n]) bounds do I c@ loop ;
: popstr ( c.. c[n] caddr len -- ) bounds do I c! loop ;
: reverse ( caddr len -- ) 2dup 2>r pushstr 2r> popstr ;</langsyntaxhighlight>
 
Forth Console Output
Line 1,539 ⟶ 1,761:
The xchars wordset offers several ways to skin this cat; this is just one way to do it, not necessarily the best one. Because the xchars wordset currently does not support recognizing combining characters, this code does not get extra credit.
 
<langsyntaxhighlight lang="forth">: xreverse {: c-addr u -- c-addr2 u :}
u allocate throw u + c-addr swap over u + >r begin ( from to r:end)
over r@ u< while
Line 1,547 ⟶ 1,769:
 
\ example use
s" ώщыē" xreverse type \ outputs "ēыщώ"</langsyntaxhighlight>
 
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<langsyntaxhighlight lang="fortran">PROGRAM Example
 
CHARACTER(80) :: str = "This is a string"
Line 1,566 ⟶ 1,788:
WRITE(*,*) str
 
END PROGRAM Example</langsyntaxhighlight>
{{out}}
This is a string
gnirts a si sihT
Another implementation that uses a recursive not-in-place algorithm:
<langsyntaxhighlight lang="fortran">program reverse_string
 
implicit none
Line 1,595 ⟶ 1,817:
end function reverse
 
end program reverse_string</langsyntaxhighlight>
{{out}}
<pre>no devil lived on
Line 1,601 ⟶ 1,823:
 
Another shorter implementation (adapted version from stackoverflow question 10605574 how-to-reverse-a-chain-of-character-fortran-90):
<langsyntaxhighlight lang="fortran"> program reverse_string
implicit none
character (80) :: cadena
Line 1,613 ⟶ 1,835:
write (*,*) cadena
!
end program reverse_string</langsyntaxhighlight>
{{out}}
<pre>
Line 1,620 ⟶ 1,842:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Function ReverseString(s As Const String) As String
Line 1,633 ⟶ 1,855:
 
Dim s As String = "asdf"
Print "'"; s; "' reversed is '"; ReverseString(s); "'"</langsyntaxhighlight>
 
{{out}}
Line 1,648 ⟶ 1,870:
 
For example, the string "g\u0308o" represents a g with combining diaeresis, followed by the letter o. Or, in other words, "g̈o". Note that while there are three Unicode codepoints, only two "graphemes" are displayed. Using Frink's smart "reverse" function preserves these combined graphemes. A naive reverse would move the diaeresis over the o instead of the g.
<langsyntaxhighlight lang="frink">println[reverse["abcdef"]]</langsyntaxhighlight>
 
=={{header|Futhark}}==
Line 1,654 ⟶ 1,876:
Futhark has no real strings beyond a little bit of syntactic sugar, so this is the same as reversing an array.
 
<syntaxhighlight lang="futhark">
<lang Futhark>
fun main(s: []i32) = s[::-1]
</syntaxhighlight>
</lang>
 
=={{header|FutureBasic}}==
<langsyntaxhighlight lang="futurebasic">void local fn DoIt
CFStringRef s1 = @"asdf", s2 = @""
include "ConsoleWindow"
long index
for index = len(s1) - 1 to 0 step -1
s2 = fn StringByAppendingString( s2, mid(s1,index,1) )
next
print s1,s2
end fn
 
window 1
dim as Str31 str
dim as long i
 
fn DoIt
str = "123456789abcdefghijk"
 
HandleEvents</syntaxhighlight>
print str
print
 
Output:<pre>
for i = str[0] to 1 step -1
asdf fdsa</pre>
print mid$( str, i, 1 );
next i
</lang>
 
Output:
<pre>
123456789abcdefghijk
 
kjihgfedcba987654321
</pre>
 
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=e32989a1ffdc4428075ca6d4cb15dfa6 Click this link to run this code]'''
<langsyntaxhighlight lang="gambas">Public Sub Main()
Dim sString As String = "asdf"
Dim sOutput As String
Line 1,695 ⟶ 1,912:
Print sOutput
End</langsyntaxhighlight>
Output:
<pre>
Line 1,702 ⟶ 1,919:
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap">Reversed("abcdef");
# "fedcba"</langsyntaxhighlight>
 
=={{header|Gema}}==
Reverse each line in the input stream. Using built in function:
<langsyntaxhighlight lang="gema">\L<U>=@reverse{$1}</langsyntaxhighlight>
Not using built in function (recursively apply substring to same rule):
<langsyntaxhighlight lang="gema">\L<U1><U>=@{$2}$1</langsyntaxhighlight>
 
=={{header|Genie}}==
Pretty sure the output capture fails the extra credit, but that may be more local setup and font installs rather than the glib functions used.
 
<langsyntaxhighlight lang="genie">[indent=4]
/*
Reverse a string, in Genie
Line 1,728 ⟶ 1,945:
 
print combining
print combining.reverse()</langsyntaxhighlight>
 
{{out}}
Line 1,741 ⟶ 1,958:
=={{header|GFA Basic}}==
 
<syntaxhighlight lang="text">
PRINT @reverse$("asdf")
'
Line 1,752 ⟶ 1,969:
RETURN result$
ENDFUNC
</syntaxhighlight>
</lang>
 
=={{header|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.
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,831 ⟶ 2,048:
r = reversePreservingCombiningCharacters(s)
fmt.Println("combining characters:", []rune(r), r)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,849 ⟶ 2,066:
=={{header|Groovy}}==
=====Solution:=====
<langsyntaxhighlight lang="groovy">println "Able was I, 'ere I saw Elba.".reverse()</langsyntaxhighlight>
{{out}}
<pre>.ablE was I ere' ,I saw elbA</pre>
 
=====Extra Credit:=====
<langsyntaxhighlight lang="groovy">def string = "as⃝df̅"
 
List combiningBlocks = [
Line 1,868 ⟶ 2,085:
}
}
println chars.reverse().join()</langsyntaxhighlight>
{{out}}
<pre>f̅ds⃝a</pre>
 
=={{header|Harbour}}==
<langsyntaxhighlight lang="visualfoxpro">FUNCTION Reverse( sIn )
 
LOCAL cOut := "", i
Line 1,881 ⟶ 2,098:
NEXT
 
RETURN cOut</langsyntaxhighlight>
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">reverse = foldl (flip (:)) []</langsyntaxhighlight>
This function as defined in the Haskell Prelude.
 
Line 1,890 ⟶ 2,107:
 
Perhaps, for example:
<langsyntaxhighlight lang="haskell">accumulatingReverse :: [a] -> [a]
accumulatingReverse lst =
let rev xs a = foldl (flip (:)) a xs
in rev lst []</langsyntaxhighlight>
 
===Supporting combining characters===
<langsyntaxhighlight lang="haskell">import Data.Char (isMark)
import Data.List (groupBy)
myReverse = concat . reverse . groupBy (const isMark)</langsyntaxhighlight>
<code>groupBy (const isMark)</code> is an unusual way of splitting a string into its combined characters
 
=={{header|HicEst}}==
<langsyntaxhighlight lang="hicest">CHARACTER string = "Hello World", tmp
 
L = LEN( string )
Line 1,911 ⟶ 2,128:
ENDDO
 
WRITE(Messagebox, Name) string </langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">procedure main(arglist)
s := \arglist[1] | "asdf"
write(s," <-> ", reverse(s)) # reverse is built-in
end</langsyntaxhighlight>
 
=={{header|Io}}==
<langsyntaxhighlight lang="io">"asdf" reverse</langsyntaxhighlight>
 
=={{Header|Insitux}}==
 
<syntaxhighlight lang="insitux">
(reverse "hello")
</syntaxhighlight>
 
=={{header|J}}==
Reverse (<tt>|.</tt>) reverses a list of items (of any shape or type).
<langsyntaxhighlight lang="j"> |.'asdf'
fdsa</langsyntaxhighlight>
Extra credit:
First, a function to determine whether a Unicode character is a combining character:
<langsyntaxhighlight lang="j"> ranges=.16b02ff 16b036f, 16b1dbf 16b1dff, 16b20cf 16b20ff, 16bfe1f 16bfe2f
iscombining=. 2 | ranges&I.</langsyntaxhighlight>
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.
<langsyntaxhighlight lang="j"> split=. (<;.1~ -.@iscombining) :. ;</langsyntaxhighlight>
 
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.
<langsyntaxhighlight lang="j"> |.&.split&.(3 u: 7&u:) 'as⃝df̅'
f̅ds⃝a</langsyntaxhighlight>
 
=={{header|Java}}==
 
<lang java>public static String reverseString(String s) {
=== Reverse Unicode Codepoints ===
return new StringBuffer(s).reverse().toString();
 
}</lang>
Reversing codepoints works in most cases when reversing single characters wherever they are encoded on multi-bytes or not. But this doesn't work for composed characters.
{{works with|Java|1.5+}}
 
<lang java5>public static String reverseString(String s) {
<syntaxhighlight lang="java">
return new StringBuilder(s).reverse().toString();
String reversed = new StringBuilder("as⃝df̅").reverse().toString(); // fd⃝sa
}</lang>
String reversed = new StringBuffer("as⃝df̅").reverse().toString(); // fd⃝sa
</syntaxhighlight>
 
Alternately, you could use a for-loop with the same issue.
 
<syntaxhighlight lang="java">
String string = "as⃝df̅";
StringBuilder reversed = new StringBuilder();
for (int index = string.length() - 1; index >= 0; index--)
reversed.append(string.charAt(index));
reversed; // fd⃝sa
</syntaxhighlight>
 
=== Reverse Unicode Graphemes ===
 
A third-party solution is to use [https://mvnrepository.com/artifact/com.ibm.icu/icu4j ICU4J].
 
A native solution, since JDK 15, is to use <code>Pattern.compile( "\\X" )</code> from <code>java.util.regex</code> to parse grapemes.
 
Another native solution, since JDK 20, is to use <code>java.text.BreakIterator</code> class that now parse graphemes correctly<ref>https://bugs.openjdk.org/browse/JDK-8291660</ref>.
 
<syntaxhighlight lang="java">
import java.text.BreakIterator;
 
public class Reverse {
/* works with Java 20+ only
* cf. https://bugs.openjdk.org/browse/JDK-8291660
*/
public static StringBuilder graphemeReverse(String text) {
BreakIterator boundary = BreakIterator.getCharacterInstance();
boundary.setText(text);
StringBuilder reversed = new StringBuilder();
int end = boundary.last();
int start = boundary.previous();
while (start != BreakIterator.DONE) {
reversed.append(text.substring(start, end));
end = start;
start = boundary.previous();
}
return reversed;
}
public static void main(String[] args) throws Exception {
String a = "as⃝df̅";
System.out.println(graphemeReverse(a)); // f̅ds⃝a
}
}
</syntaxhighlight>
 
=={{header|JavaScript}}==
 
===ES5 Unicode ===
 
==== Split code points ====
 
<code><nowiki>split('')</nowiki></code> (with empty string argument) works only for ASCII. For Unicode strings, one of the two following methods can be used.
 
<syntaxhighlight lang="javascript">
example = 'Tux 🐧 penguin';
 
// array expansion operator
[...example].reverse().join('') // 'niugnep 🐧 xuT'
// split regexp separator with Unicode mode
example.split(/(?:)/u).reverse().join('') // 'niugnep 🐧 xuT'
 
// do not use
example.split('').reverse().join(''); // 'niugnep \udc27\ud83d xuT'
</syntaxhighlight>
 
==== Split graphemes =====
 
More generally, one would want to combine characters such as joining emojis or diacritics to be handled properly so enumerating over graphemes is a must.
 
<syntaxhighlight lang="javascript">
a = "\u{1F466}\u{1F3FB}\u{1f44b}"; // '👦🏻👋'
 
// wrong behavior - ASCII sequences
a.split('').reverse().join(''); // '\udc4b🁦\ud83d'
 
// wrong behavior - Unicode code points
[...a].reverse().join(''); // '👋🏻👦'
a.split(/(?:)/u).reverse().join(''); // '👋🏻👦'
 
// correct behavior - Unicode graphemes
[...new Intl.Segmenter().segment(a)].map(x => x.segment).reverse().join('') // 👋👦🏻
</syntaxhighlight>
 
=== ASCII ===
 
==== ES5 ====
 
<langsyntaxhighlight lang="javascript">//using chained methods
function reverseStr(s) {
return s.split('').reverse().join('');
Line 1,966 ⟶ 2,274:
while (i--) o += s[i];
return o;
}</langsyntaxhighlight>
 
==== ES6 ====
 
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
 
// .reduceRight() can be useful when reversals
Line 1,987 ⟶ 2,295:
.map(f => f("Some string to be reversed"));
 
})();</langsyntaxhighlight>
 
{{Out}}
<langsyntaxhighlight JavaScriptlang="javascript">["desrever <- eb <- ot <- gnirts <- emoS", "desrever eb ot gnirts emoS"]</langsyntaxhighlight>
 
=={{header|Joy}}==
<syntaxhighlight lang="joy">DEFINE reverse == "" [swons] fold.
 
"asdf" reverse putchars.</syntaxhighlight>
{{out}}
<pre>fdsa</pre>
 
=={{header|jq}}==
jq's explode/implode filters are based on codepoints, and therefore "reverse_string" as defined here will reverse the sequence of codepoints.
The topic of Unicode combining characters is a large one that is not touched on here.
<langsyntaxhighlight lang="jq">def reverse_string: explode | reverse | implode;</langsyntaxhighlight>
'''Examples''':
"nöel" | reverse_string # => "leön"
Line 2,005 ⟶ 2,320:
 
Jsi only supports UTF-8 literals so far (in release 2.8), character by character manipulation routines of multibyte UTF-8 data will not be correct. No extra credit, ''yet''.
<langsyntaxhighlight lang="javascript">var str = "Never odd or even";
puts(str);
puts(str.split('').reverse().join(''));</langsyntaxhighlight>
{{out}}
<pre>Never odd or even
Line 2,013 ⟶ 2,328:
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">julia> reverse("hey")
"yeh"</langsyntaxhighlight>
The <code>reverse</code> function reverses codepoints ([https://github.com/JuliaLang/julia/issues/6165 because this is the right behavior] for the main application of string reversal: reversed string processing by external C libraries). However, [https://github.com/JuliaLang/julia/pull/9261 starting in Julia 0.4], you can also reverse the graphemes if you want (i.e. to reverse "visual order" including combining characters etc.) by:
<langsyntaxhighlight lang="julia">julia> join(reverse(collect(graphemes("as⃝df̅"))))
"f̅ds⃝a"</langsyntaxhighlight>
 
=={{header|K}}==
Monadic reverse (| ) verb reverses a string or list of any shape
<syntaxhighlight lang="k">
<lang K>
|"asdf"
"fdsa"
Line 2,027 ⟶ 2,342:
| 23 4 5 1
1 5 4 23
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="kotlin">fun main(args: Array<String>) {
println("asdf".reversed())
}</langsyntaxhighlight>
 
=={{header|L++}}==
<langsyntaxhighlight lang="lisp">(include "string" "algorithm")
(main
(decl std::string s)
(std::getline std::cin s)
(std::reverse (s.begin) (s.end))
(prn s))</langsyntaxhighlight>
 
=={{header|LabVIEW}}==
Line 2,046 ⟶ 2,361:
 
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
<lang Scheme>
{S.reverse hello brave new world}
-> world new brave hello
</syntaxhighlight>
</lang>
 
=={{header|Lang}}==
<syntaxhighlight lang="lang">
# Inv operator
fn.println(parser.op(-asdf))
# Ouput: fdsa
 
# Inv operator function
fn.println(fn.inv(asdf))
# Ouput: fdsa
</syntaxhighlight>
 
=={{header|Lang5}}==
<langsyntaxhighlight lang="lang5">: flip "" split reverse "" join ;
"qwer asdf" flip .</langsyntaxhighlight>
 
=={{header|langur}}==
ThisThe accountsreverse() forfunction codewill points,reverse buta notstring foraccording to graphemes.
<langsyntaxhighlight lang="langur">writeln cp2s reverse s2cp q("don't you know)"</langsyntaxhighlight>
 
{{out}}
Line 2,063 ⟶ 2,389:
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">local(input) = 'asdf'
#input->reverse</langsyntaxhighlight>
 
===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.
<langsyntaxhighlight Lassolang="lasso">local(input = 'asdf', output = array)
with i in #input->values
do #output->insertFirst(#i)
#output->join</langsyntaxhighlight>
 
=={{header|LC3 Assembly}}==
A string is stored as a zero-terminated array of character codes. To reverse it, we first scan forwards until we find the end; we then move backwards again, copying each code into a block of memory we have reserved for the purpose; and finally, when we have got back to the beginning, we append a terminal zero to the new string we have created. We can then call <tt>PUTS</tt> to print it.
<langsyntaxhighlight lang="lc3asm"> .ORIG 0x3000
 
LEA R1,STRING
Line 2,110 ⟶ 2,436:
GNIRTS .BLKW 128
 
.END</langsyntaxhighlight>
{{out}}
<pre>d'gnahc woh !n'llaf woh O tub -- eh tseeb uoht fI</pre>
Line 2,117 ⟶ 2,443:
 
Ordinary string:
<langsyntaxhighlight lang="lisp">
> (lists:reverse "asdf")
"fdsa"
</syntaxhighlight>
</lang>
 
Create a UTF-8 encoded string:
<langsyntaxhighlight lang="lisp">
> (set encoded (binary ("åäö ð" utf8)))
#B(195 165 195 164 195 182 32 195 176)
</syntaxhighlight>
</lang>
 
Display it, to be sure:
<langsyntaxhighlight lang="lisp">
> (io:format "~tp~n" (list encoded))
<<"åäö ð"/utf8>>
</syntaxhighlight>
</lang>
 
Reverse it:
<langsyntaxhighlight lang="lisp">
> (lists:reverse (unicode:characters_to_list encoded))
"ð öäå"
</syntaxhighlight>
</lang>
 
=={{header|Liberty BASIC}}==
{{works with|Just BASIC}}
<lang lb>input$ ="abcdefgABCDEFG012345"
{{works with|Run BASIC}}
<syntaxhighlight lang="lb">input$ ="abcdefgABCDEFG012345"
print input$
print ReversedStr$( input$)
Line 2,151 ⟶ 2,479:
ReversedStr$ =ReversedStr$ +mid$( in$, i, 1)
next i
end function</langsyntaxhighlight>
 
=={{header|Lingo}}==
Lingo strings are always UTF-8 encoded and string operations are based on Unicode code points, so the "extra credit" is built-in:
<langsyntaxhighlight lang="lingo">on reverse (str)
res = ""
repeat with i = str.length down to 1
Line 2,161 ⟶ 2,489:
end repeat
return res
end</langsyntaxhighlight>
To reverse a string byte-wise, the ByteArray data type has to be used:
<langsyntaxhighlight lang="lingo">on reverseBytes (str)
ba = byteArray(str)
res = byteArray()
Line 2,170 ⟶ 2,498:
end repeat
return res
end</langsyntaxhighlight>
 
=={{header|LiveCode}}==
<langsyntaxhighlight lang="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</langsyntaxhighlight>
 
=={{header|LLVM}}==
<langsyntaxhighlight lang="llvm">; This is not strictly LLVM, as it uses the C library function "printf".
; LLVM does not provide a way to print values, so the alternative would be
; to just load the string into memory, and that would be boring.
Line 2,267 ⟶ 2,595:
declare void @llvm.memcpy.p0i8.p0i8.i64(i8* nocapture writeonly, i8* nocapture readonly, i64, i32, i1)
 
declare i64 @strlen(i8*)</langsyntaxhighlight>
{{out}}
<pre>Hello world
Line 2,274 ⟶ 2,602:
=={{header|Logo}}==
REVERSE works on both words and lists.
<langsyntaxhighlight lang="logo">print reverse "cat ; tac</langsyntaxhighlight>
 
=={{header|Lua}}==
Built-in string.reverse(s) or s:reverse().
 
<lang lua>theString = theString:reverse()</lang>
=== ASCII ===
 
<syntaxhighlight lang="lua">
example = 'asdf'
string.reverse(example) -- fdsa
example:reverse() -- fdsa
</syntaxhighlight>
 
=== Unicode ===
 
Lua doesn't support Unicode strings.
 
=={{header|M2000 Interpreter}}==
===Using Custom Function===
Version 2, using insert to string (with no copies of strings)
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module ReverseString {
a$="as⃝df̅"
Line 2,310 ⟶ 2,649:
}
ReverseString
</syntaxhighlight>
</lang>
 
===using StrRev$()===
this function (new to 9.5 version) use StrReverse from Vb6
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
a$="as⃝df̅"
b$=strrev$(a$)
clipboard b$
Print b$="̅fd⃝sa"
</syntaxhighlight>
</lang>
 
=={{header|M4}}==
<langsyntaxhighlight lang="m4">define(`invert',`ifelse(len(`$1'),0,,`invert(substr(`$1',1))'`'substr(`$1',0,1))')</langsyntaxhighlight>
 
=={{header|Maclisp}}==
<langsyntaxhighlight lang="lisp">(readlist (reverse (explode "my-string")))</langsyntaxhighlight>
Output:
<pre>"gnirts-ym"</pre>
 
=={{header|MACRO-11}}==
<syntaxhighlight lang="macro11"> .TITLE REVERS
.MCALL .GTLIN,.PRINT,.EXIT
REVERS::.GTLIN #1$ ; READ STRING
MOV #1$,R0
JSR PC,REV ; REVERSE IT
.PRINT #1$ ; PRINT RESULT
.EXIT
1$: .BLKB 200
 
; REVERSE STRING AT R0
REV: MOV R0,R1
1$: TSTB (R1)+ ; FIND END OF STRING
BNE 1$
DEC R1 ; MOVE BACK TO LAST CHAR
2$: MOVB -(R1),R2 ; SWAP CHARS
MOVB (R0),(R1)
MOVB R2,(R0)+
CMP R0,R1 ; STOP WHEN POINTERS MEET
BLT 2$
RTS PC
 
.END REVERS</syntaxhighlight>
{{out}}
<pre>.revers
A man, a plan, a canal: Panama
amanaP :lanac a ,nalp a ,nam A</pre>
 
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple">> StringTools:-Reverse( "foo" );
"oof"</langsyntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight lang="mathematica">StringReverse["asdf"]</langsyntaxhighlight>
 
=={{header|MATLAB}}==
Line 2,340 ⟶ 2,707:
 
Sample Usage:
<langsyntaxhighlight MATLABlang="matlab">>> 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</langsyntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">sreverse("abcdef"); /* "fedcba" */
 
sreverse("rats live on no evil star"); /* not a bug :o) */</langsyntaxhighlight>
 
=={{header|MAXScript}}==
<langsyntaxhighlight lang="maxscript">fn reverseString s =
(
local reversed = ""
for i in s.count to 1 by -1 do reversed += s[i]
reversed
)</langsyntaxhighlight>
 
=={{header|min}}==
{{works with|min|0.19.3}}
<langsyntaxhighlight lang="min">("" split reverse "" join) :reverse-str</langsyntaxhighlight>
 
=={{header|MiniScript}}==
<langsyntaxhighlight MiniScriptlang="miniscript">str = "This is a string"
print "Forward: " + str
newStr = ""
Line 2,371 ⟶ 2,738:
newStr = newStr + str[i]
end for
print "Reversed: " + newStr</langsyntaxhighlight>
{{out}}
<pre>
Line 2,380 ⟶ 2,747:
=={{header|MIPS Assembly}}==
 
<langsyntaxhighlight lang="mips">
# First, it gets the length of the original string
# Then, it allocates memory from the copy
Line 2,416 ⟶ 2,783:
ex_msg_cpy: .asciiz "\nCopied string:\n"
string: .asciiz "Nice string you got there!\n"
</syntaxhighlight>
</lang>
 
=={{header|Mirah}}==
<langsyntaxhighlight lang="mirah">def reverse(s:string)
StringBuilder.new(s).reverse
end
 
puts reverse('reversed')</langsyntaxhighlight>
 
=={{header|Miranda}}==
<syntaxhighlight lang="miranda">main :: [sys_message]
main = [Stdout (reverse "esreveR"),
Stdout "\n"]</syntaxhighlight>
{{out}}
<pre>Reverse</pre>
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">MODULE ReverseStr;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT Write,WriteString,WriteLn,ReadChar;
Line 2,465 ⟶ 2,839:
 
ReadChar
END ReverseStr.</langsyntaxhighlight>
 
=={{header|Modula-3}}==
<langsyntaxhighlight lang="modula3">MODULE Reverse EXPORTS Main;
 
IMPORT IO, Text;
Line 2,483 ⟶ 2,857:
BEGIN
IO.Put(String("Foobarbaz") & "\n");
END Reverse.</langsyntaxhighlight>
{{out}}
<pre>
Line 2,490 ⟶ 2,864:
 
=={{header|MUMPS}}==
<langsyntaxhighlight MUMPSlang="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</langsyntaxhighlight>
{{out}}
<pre>
Line 2,504 ⟶ 2,878:
 
=={{header|Nanoquery}}==
<langsyntaxhighlight Nanoquerylang="nanoquery">def reverse(string)
l = ""
 
Line 2,512 ⟶ 2,886:
 
return l
end</langsyntaxhighlight>
 
=={{header|Neko}}==
No extra credit for UTF in this example.
<langsyntaxhighlight lang="actionscript">/* Reverse a string, in Neko */
 
var reverse = function(s) {
Line 2,545 ⟶ 2,919:
str = ""
$print(str, "\n")
$print(reverse(str), "\n")</langsyntaxhighlight>
{{out}}
<pre>prompt$ nekoc reverse.neko
Line 2,566 ⟶ 2,940:
===Supporting Combining Characters===
Compile with:<pre>ncc -reference:System.Windows.Forms reverse.n</pre>
<langsyntaxhighlight Nemerlelang="nemerle">using System;
using System.Globalization;
using System.Windows.Forms;
Line 2,588 ⟶ 2,962:
MessageBox.Show($"$test --> $(UReverse(test))"); //for whatever reason my console didn't display Unicode properly, but a MessageBox worked
}
}</langsyntaxhighlight>
===Basic Reverse===
Doesn't require the '''System.Globalization''' namespace, probably a little less overhead.
<langsyntaxhighlight Nemerlelang="nemerle">Reverse(text : string) : string
{
mutable output = [];
Line 2,597 ⟶ 2,971:
output ::= c.ToString();
Concat("", output)
}</langsyntaxhighlight>
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
 
options replace format comments java crossref savelog symbols nobinary
Line 2,610 ⟶ 2,984:
say sihTesrever
 
return</langsyntaxhighlight>
{{out}}
<pre>
Line 2,618 ⟶ 2,992:
 
=={{header|NewLISP}}==
<langsyntaxhighlight NewLISPlang="newlisp">(reverse "!dlroW olleH")</langsyntaxhighlight>
 
=={{header|Nial}}==
<langsyntaxhighlight lang="nial">reverse 'asdf'
=fdsa</langsyntaxhighlight>
 
=={{header|Nim}}==
<lang nim>import unicode
 
=== Unicode codepoints ===
proc reverse(s: var string) =
for i in 0 .. s.high div 2:
swap(s[i], s[s.high - i])
 
Since Nim 0.11.0, the <code>unicode</code> module provides a [https://nim-lang.github.io/Nim/unicode.html#reversed%2Cstring <code>reversed</code>] proc...
proc reversed(s: string): string =
Hence:
result = newString(s.len)
for i,c in s:
result[s.high - i] = c
 
<syntaxhighlight lang="nim">
proc uniReversed(s: string): string =
import unicode
result = newStringOfCap(s.len)
var tmp: seq[Rune] = @[]
for r in runes(s):
tmp.add(r)
for i in countdown(tmp.high, 0):
result.add(toUtf8(tmp[i]))
 
doAssert "foobar".reversed == "raboof"
proc isComb(r: Rune): bool =
doAssert "先秦兩漢".reversed == "漢兩秦先"
(r >=% Rune(0x300) and r <=% Rune(0x36f)) or
</syntaxhighlight>
(r >=% Rune(0x1dc0) and r <=% Rune(0x1dff)) or
(r >=% Rune(0x20d0) and r <=% Rune(0x20ff)) or
(r >=% Rune(0xfe20) and r <=% Rune(0xfe2f))
 
This proc is enumerating codepoints so it will work with Unicode multi-bytes characters. A special handling was added so it's supports composing as well but since it's not enumerating graphemes it won't work with joining.
proc uniReversedPreserving(s: string): string =
result = newStringOfCap(s.len)
var tmp: seq[Rune] = @[]
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]))
 
=== Unicode graphemes ===
for str in ["Reverse This!", "as⃝df̅"]:
echo "Original string: ", str
echo "Reversed: ", reversed(str)
echo "UniReversed: ", uniReversed(str)
echo "UniReversedPreserving: ", uniReversedPreserving(str)</lang>
{{out}}
<pre>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</pre>
 
There is no native method to handle grapheme currently.
Since Nim 0.11.0, the ''unicode'' module provides a ''reversed'' proc...
Hence:
 
<lang nim>import unicode
 
doAssert "foobar".reversed == "raboof"
doAssert "先秦兩漢".reversed == "漢兩秦先"</lang>
 
=={{header|NS-HUBASIC}}==
<langsyntaxhighlight NSlang="ns-HUBASIChubasic">10 STRING$="THIS TEXT IS REVERSED."
20 REVERSED$=""
30 FOR I=1 TO LEN(STRING$)
40 REVERSED$=MID$(STRING$,I,1)+REVERSED$
50 NEXT
60 PRINT REVERSED$</langsyntaxhighlight>
 
=={{header|Oberon-2}}==
Tested with [https://miasap.se/obnc OBNC].
<langsyntaxhighlight Oberonlang="oberon">MODULE reverse;
 
IMPORT Out, Strings;
Line 2,719 ⟶ 3,055:
Out.String(s);
Out.Ln
END reverse.</langsyntaxhighlight>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
result := "asdf"->Reverse();
</syntaxhighlight>
</lang>
 
=={{header|Objective-C}}==
This extends the <code>NSString</code> object adding a <code>reverseString</code> class method.
<langsyntaxhighlight lang="objc">#import <Foundation/Foundation.h>
 
@interface NSString (Extended)
Line 2,747 ⟶ 3,083:
return rtr;
}
@end</langsyntaxhighlight>
Usage example:
<langsyntaxhighlight lang="objc">int main()
{
@autoreleasepool {
Line 2,759 ⟶ 3,095:
}
return 0;
}</langsyntaxhighlight>
===Supporting combining characters===
Extra credit
<langsyntaxhighlight lang="objc">#import <Foundation/Foundation.h>
 
@interface NSString (Extended)
Line 2,781 ⟶ 3,117:
return ostr;
}
@end</langsyntaxhighlight>
Usage example:
<langsyntaxhighlight lang="objc">int main()
{
@autoreleasepool {
Line 2,793 ⟶ 3,129:
}
return 0;
}</langsyntaxhighlight>
 
=={{header|OCaml}}==
Line 2,802 ⟶ 3,138:
 
{{works with|OCaml|4.02+}}
<langsyntaxhighlight lang="ocaml">let string_rev s =
let len = String.length s in
String.init len (fun i -> s.[len - 1 - i])
 
let () =
print_endline (string_rev "Hello world!")</langsyntaxhighlight>
 
for in place modification we can't use strings anymore because strings became immutable in ocaml 4.02, so the type bytes has to be used instead:
 
<langsyntaxhighlight lang="ocaml">let rev_bytes bs =
let last = Bytes.length bs - 1 in
for i = 0 to last / 2 do
Line 2,825 ⟶ 3,161:
print_bytes s;
print_newline ();
;;</langsyntaxhighlight>
 
Here is a 100% functionnal string reversing function:
<langsyntaxhighlight lang="ocaml">let rec revs_aux strin list index =
if List.length list = String.length strin
then String.concat "" list
Line 2,836 ⟶ 3,172:
 
let () =
print_endline (revs "Hello World!")</langsyntaxhighlight>
 
will return "!dlroW olleH"
 
=={{header|Octave}}==
<langsyntaxhighlight lang="octave">s = "a string";
rev = s(length(s):-1:1)</langsyntaxhighlight>
 
=={{header|Oforth}}==
<syntaxhighlight lang Oforth="oforth">reverse</langsyntaxhighlight>
 
=={{header|Ol}}==
<langsyntaxhighlight lang="scheme">
(define (rev s)
(runes->string (reverse (string->runes s))))
Line 2,855 ⟶ 3,191:
(print (rev "Hello, λ!"))
; ==> !λ ,olleH
</syntaxhighlight>
</lang>
 
=={{header|OOC}}==
<langsyntaxhighlight lang="ooc">
main: func {
"asdf" reverse() println() // prints "fdsa"
}
</syntaxhighlight>
</lang>
 
=={{header|OpenEdge/Progress}}==
<langsyntaxhighlight OpenEdgelang="openedge/Progressprogress">FUNCTION reverseString RETURNS CHARACTER (
INPUT i_c AS CHARACTER
):
Line 2,879 ⟶ 3,215:
END FUNCTION.
 
MESSAGE reverseString( "asdf" ) VIEW-AS ALERT-BOX.</langsyntaxhighlight>
 
=={{header|OxygenBasic}}==
<langsyntaxhighlight lang="oxygenbasic">
 
'8 BIT CHARACTERS
Line 2,916 ⟶ 3,252:
'
print s
</syntaxhighlight>
</lang>
 
==OxygenBasic x86 Assembler==
32 bit code, 8-bit characters:
<langsyntaxhighlight lang="oxygenbasic">
 
string s="qwertyuiop"
Line 2,941 ⟶ 3,277:
 
print s
</syntaxhighlight>
</lang>
 
=={{header|Oz}}==
Strings are lists. A function "Reverse" defined on lists is part of the implementation.
<langsyntaxhighlight lang="oz">{System.showInfo {Reverse "!dlroW olleH"}}</langsyntaxhighlight>
An efficient (tail-recursive) implementation could look like this:
<langsyntaxhighlight lang="oz">local
fun {DoReverse Xs Ys}
case Xs of nil then Ys
Line 2,955 ⟶ 3,291:
in
fun {Reverse Xs} {DoReverse Xs nil} end
end</langsyntaxhighlight>
Oz uses a single-byte encoding by default. If you decide to use a multi-byte encoding, Reverse will not work correctly.
 
Line 2,961 ⟶ 3,297:
 
===Version #1.===
<langsyntaxhighlight lang="parigp">reverse(s)=concat(Vecrev(s))</langsyntaxhighlight>
 
===Version #2.===
{{Works with|PARI/GP|2.7.4 and above}}
 
<langsyntaxhighlight lang="parigp">
\\ Return reversed string str.
\\ 3/3/2016 aev
Line 2,979 ⟶ 3,315:
for(i=1,n, sr=sreverse(s));
}
</langsyntaxhighlight>
 
{{Output}}
Line 2,989 ⟶ 3,325:
</pre>
 
<langsyntaxhighlight lang="parigp">
\\ Version #1 upgraded to complete function. Practically the same.
reverse(str)={return(concat(Vecrev(str)))}
Line 3,001 ⟶ 3,337:
for(i=1,n, sr=reverse(s));
}
</langsyntaxhighlight>
 
{{Output}}
Line 3,017 ⟶ 3,353:
 
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).
<langsyntaxhighlight 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
Line 3,025 ⟶ 3,361:
for i := 0 to len-1 do
result[min1 + len-1 - i] := s[min + i]
end;</langsyntaxhighlight>
<langsyntaxhighlight lang="pascal">{Copy and paste it in your program}
function revstr(my_s:string):string;
var out_s:string;
Line 3,035 ⟶ 3,371:
out_s:=out_s+my_s[ls-i+1];
revstr:=out_s;
end;</langsyntaxhighlight>
=== Extended Pascal, Turbo Pascal, Delphi and compatible compilers ===
<langsyntaxhighlight lang="pascal">function reverse(s:string):string;
var i:integer;
var tmp:char;
Line 3,048 ⟶ 3,384:
reverse:=s;
end;
end;</langsyntaxhighlight>
alternative as procedure which changes the original
<langsyntaxhighlight lang="pascal">procedure revString(var s:string);
var
i,j:integer;
Line 3,065 ⟶ 3,401:
dec(j)
end;
end;</langsyntaxhighlight>
 
=={{header|Peloton}}==
Padded out, variable length Chinese dialect
<langsyntaxhighlight lang="sgml"><# 显示 指定 变量 反转顺序 字串>集装箱|猫坐在垫子</#></langsyntaxhighlight>
This assigns the reverse of 'the cat sat on the mat' to the variable 'container' and displays the result which is <pre>子垫在坐猫</pre> which Google Translate renders as <pre>Sub-pad sitting cat</pre>.
 
The same again but with everything in Korean.
<langsyntaxhighlight lang="sgml"><# 보이십 할당하 변물건 열거꾸 문자그>컨테이너|고양이가 매트 위에 앉아</#></langsyntaxhighlight>
Reversing the Korean makes an untranslatable-by-Google mess of the sentence, viz <pre>아앉 에위 트매 가이양고</pre>.
 
The short-opcode version in English dialect is
<langsyntaxhighlight lang="sgml"><@ SAYLETVARREVLIT>集装箱|猫坐在垫子</@></langsyntaxhighlight>
Peloton works in Unicode.
 
=={{header|Perl}}==
 
<lang perl>use utf8;
[https://perldoc.perl.org/functions/reverse reverse()] works in the context of a List or a scalar, not a string.
 
<syntaxhighlight lang="perl">use utf8;
binmode STDOUT, ":utf8";
 
# to reverse characters (code points):
print scalar reverse('visor'), "\n";
 
# to reverse graphemes:
Line 3,091 ⟶ 3,430:
 
$string = 'ℵΑΩ 駱駝道 🤔 🇸🇧 🇺🇸 🇬🇧‍ 👨‍👩‍👧‍👦🆗🗺';
print join("", reverse $string =~ /\X/g), "\n";</langsyntaxhighlight>
{{out}}
<pre>rosiv
Line 3,098 ⟶ 3,437:
 
=={{header|Pharo}}==
<syntaxhighlight lang Pharo="pharo">'123' reversed</langsyntaxhighlight>
 
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>?reverse("asdf")</lang>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">reverse</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"asdf"</span><span style="color: #0000FF;">)</span>
However that would go horribly wrong on utf8 strings, even without combining characters, so... this seems ok on "as\u203Ddf\u0305", as long as it is displayed in a message box rather than a Windows Console (even with chcp 65001 and Lucida Console, the characters do not combine).<br>
<!--</syntaxhighlight>-->
However that would go horribly wrong on utf8 strings, even without combining characters, so... this seems ok on "as\u203Ddf\u0305", as long as it is displayed in a message box rather than a Windows Console (even with chcp 65001 and Lucida Console, the characters do not combine). It actually works better under pwa/p2js than on desktop/Phix, you can find a copy of this code in demo/HelloUTF8.exw which outputs the result in a message box and therefore looks much better on the latter.<br>
Note that [[XXXX_redacted#Phix]] adds some ZERO-WIDTH-JOINER handling to the inner code.
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>function unicode_reverse(string utf8)
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
sequence utf32 = utf8_to_utf32(utf8)
<span style="color: #008080;">function</span> <span style="color: #000000;">unicode_reverse</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">utf8</span><span style="color: #0000FF;">)</span>
integer ch
<span style="color: #004080;">sequence</span> <span style="color: #000000;">utf32</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">utf8_to_utf32</span><span style="color: #0000FF;">(</span><span style="color: #000000;">utf8</span><span style="color: #0000FF;">)</span>
-- The assumption is made that <char><comb1><comb2>
<span style="color: #000080;font-style:italic;">-- The assumption is made that &lt;char&gt;&lt;comb1&gt;&lt;comb2&gt;
-- and <char><comb2><comb1> etc would work the same.
-- and &lt;char&gt;&lt;comb2&gt;&lt;comb1&gt; etc would work the same.
-- The following loop converts <char><comb1><comb2>
-- The following loop converts &lt;char&gt;&lt;comb1&gt;&lt;comb2&gt;
-- to <comb1><comb2><char>, as a pre-reverse() step.
-- to &lt;comb1&gt;&lt;comb2&gt;&lt;char&gt;, as a pre-reverse() step.</span>
for i=1 to length(utf32) do
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">utf32</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
ch = utf32[i]
<span style="color: #004080;">integer</span> <span style="color: #000000;">ch</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">utf32</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
if (ch>=0x300 and ch<=0x36f)
<span style="color: #008080;">if</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">>=</span><span style="color: #000000;">0x300</span> <span style="color: #008080;">and</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;"><=</span><span style="color: #000000;">0x36f</span><span style="color: #0000FF;">)</span>
or (ch>=0x1dc0 and ch<=0x1dff)
<span style="color: #008080;">or</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">>=</span><span style="color: #000000;">0x1dc0</span> <span style="color: #008080;">and</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;"><=</span><span style="color: #000000;">0x1dff</span><span style="color: #0000FF;">)</span>
or (ch>=0x20d0 and ch<=0x20ff)
<span style="color: #008080;">or</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">>=</span><span style="color: #000000;">0x20d0</span> <span style="color: #008080;">and</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;"><=</span><span style="color: #000000;">0x20ff</span><span style="color: #0000FF;">)</span>
or (ch>=0xfe20 and ch<=0xfe2f) then
<span style="color: #008080;">or</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">>=</span><span style="color: #000000;">0xfe20</span> <span style="color: #008080;">and</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;"><=</span><span style="color: #000000;">0xfe2f</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
utf32[i] = utf32[i-1]
<span style="color: #000000;">utf32</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">utf32</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
utf32[i-1] = ch
<span style="color: #000000;">utf32</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">ch</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
utf32 = reverse(utf32)
<span style="color: #000000;">utf32</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">reverse</span><span style="color: #0000FF;">(</span><span style="color: #000000;">utf32</span><span style="color: #0000FF;">)</span>
utf8 = utf32_to_utf8(utf32)
<span style="color: #000000;">utf8</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">utf32_to_utf8</span><span style="color: #0000FF;">(</span><span style="color: #000000;">utf32</span><span style="color: #0000FF;">)</span>
return utf8
<span style="color: #008080;">return</span> <span style="color: #000000;">utf8</span>
end function</lang>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">r4</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"as\u203Ddf\u0305"</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">rt</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">r4</span><span style="color: #0000FF;">&</span><span style="color: #008000;">" reversed is "</span><span style="color: #0000FF;">&</span><span style="color: #000000;">unicode_reverse</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r4</span><span style="color: #0000FF;">)&</span><span style="color: #008000;">"\n"</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">rt</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
 
=={{header|PHP}}==
 
<lang php>strrev($string);</lang>
=== Unicode ===
 
==== Code points ====
 
If you want Unicode support, you have to use some multibyte function. Sadly, PHP doesn't contain <code>mb_strrev()</code>. One of functions which support Unicode and is useful in this case is <code>preg_split()</code>.
<syntaxhighlight lang="php">
<lang php>// Will split every Unicode character to array, reverse array and will convert it to string.
// 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>
join('', array_reverse(preg_split('""u', $string, -1, PREG_SPLIT_NO_EMPTY)));
</syntaxhighlight>
 
With PHP 7.4+ and 8+, it's also possible to use <code>mb_str_split()</code>, which may ends easier.
 
<syntaxhighlight lang="php">
implode('', array_reverse(mb_str_split($string)));
</syntaxhighlight>
 
==== Graphemes ====
 
When using combining characters such as diacritics or ZWJ (joining), reversing code points will mess with the result, reversing the graphemes instead is mandatory. This is generally the best and safest approach. As there is no <code>grapheme_reverse()</code> function or grapheme iterator, one has to implement it with <code>grapheme_strlen</code> and <code>grapheme_substr</code>. In PHP, there is no Unicode escape sequence so to specify characters by code point a tricks must be used: for example, using the escape sequence of HTML entities and then convert it to a Unicode encoding such as UTF-8.
 
<syntaxhighlight lang="php">
$a = mb_convert_encoding('&#x1F466;&#x1F3FB;&#x1f44b;', 'UTF-8', 'HTML-ENTITIES'); // 👦🏻👋
 
function str_to_array($string)
{
$length = grapheme_strlen($string);
$ret = [];
 
for ($i = 0; $i < $length; $i += 1) {
 
$ret[] = grapheme_substr($string, $i, 1);
}
 
return $ret;
}
 
function utf8_strrev($string)
{
return implode(array_reverse(str_to_array($string)));
}
 
print_r(utf8_strrev($a)); // 👋👦🏻
</syntaxhighlight>
 
=== ASCII ===
 
<syntaxhighlight lang="php">strrev($string);</syntaxhighlight>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(pack (flip (chop "äöüÄÖÜß")))</langsyntaxhighlight>
{{out}}
<pre>-> "ßÜÖÄüöä"</pre>
Line 3,140 ⟶ 3,530:
=={{header|Pike}}==
For simple ASCII:
<langsyntaxhighlight Pikelang="pike">reverse("foo");</langsyntaxhighlight>
{{out}}
<pre>"oof"</pre>
Line 3,149 ⟶ 3,539:
if sent raw wide strings.
 
<langsyntaxhighlight Pikelang="pike">#charset utf8
void main()
{
string s = "ßÜÖÄüöää ἀρχῇ";
write("%s\n", string_to_utf8( reverse(s) ));
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,161 ⟶ 3,551:
 
=={{header|PL/I}}==
<langsyntaxhighlight PLlang="pl/Ii">s = reverse(s);</langsyntaxhighlight>
 
=={{header|Plain English}}==
<langsyntaxhighlight lang="plainenglish">To run:
Start up.
Put "asdf" into a string.
Reverse the string.
Shut down.</langsyntaxhighlight>
 
=={{header|plainTeX}}==
Works well if the string has no space (spaces are gobbled).
 
<langsyntaxhighlight lang="tex">\def\gobtoA#1\revA{}\def\gobtoB#1\revB{}
\def\reverse#1{\reversei{}#1\revA\revB\revB\revB\revB\revB\revB\revB\revB\revA}
\def\reversei#1#2#3#4#5#6#7#8#9{\gobtoB#9\revend\revB\reversei{#9#8#7#6#5#4#3#2#1}}
\def\revend\revB\reversei#1#2\revA{\gobtoA#1}
\reverse{Rosetta}
\bye</langsyntaxhighlight>
 
Output:
Line 3,184 ⟶ 3,574:
 
=={{header|Pop11}}==
<langsyntaxhighlight lang="pop11">define reverse_string(s);
lvars i, l = length(s);
for i from l by -1 to 1 do
Line 3,190 ⟶ 3,580:
endfor;
consstring(l);
enddefine;</langsyntaxhighlight>
 
=={{header|PostScript}}==
The following implementation works on arrays of numerics as well as characters ( string ).
<langsyntaxhighlight PostScriptlang="postscript">/reverse{
/str exch def
/temp str 0 get def
Line 3,205 ⟶ 3,595:
}repeat
str pstack
}def</langsyntaxhighlight>
{{Out}}
<langsyntaxhighlight PostScriptlang="postscript">[1 2 3] reverse % input
[3 2 1]
 
(Hello World) reverse % input
(dlroW olleH)</langsyntaxhighlight>
 
=={{header|PowerBASIC}}==
<langsyntaxhighlight lang="powerbasic">#DIM ALL
#COMPILER PBCC 6
 
FUNCTION PBMAIN () AS LONG
CON.PRINT STRREVERSE$("PowerBASIC")
END FUNCTION</langsyntaxhighlight>
 
=={{header|PowerShell}}==
 
=== For ASCII ===
 
Test string
<langsyntaxhighlight lang="powershell">$s = "asdf"</langsyntaxhighlight>
====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|1}}
<langsyntaxhighlight lang="powershell">[string]::Join('', $s[$s.Length..0])</langsyntaxhighlight>
{{works with|PowerShell|2}}
<langsyntaxhighlight lang="powershell">-join ($s[$s.Length..0])</langsyntaxhighlight>
{{works with|PowerShell|2}}
<syntaxhighlight lang ="powershell">[array]::Reverse($s)</langsyntaxhighlight>
====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|1}}
<langsyntaxhighlight lang="powershell">$s -replace
('(.)' * $s.Length),
[string]::Join('', ($s.Length..1 | ForEach-Object { "`$$_" }))</langsyntaxhighlight>
{{works with|PowerShell|2}}
<langsyntaxhighlight lang="powershell">$s -replace
('(.)' * $s.Length),
-join ($s.Length..1 | ForEach-Object { "`$$_" } )</langsyntaxhighlight>
{{works with|PowerShell|3}}
<syntaxhighlight lang="powershell">
<lang PowerShell>
[Regex]::Matches('abc'$s,'.','RightToLeft').Value -join ''
</syntaxhighlight>
</lang>
 
{{Out}}
=== For Unicode ===
<pre>
 
cba
==== For codepoints ====
</pre>
 
Since PowerShell 7, there is a <code>EnumerateRunes()</code> method to enumerate Unicode codepoints. Enumerating codepoints works for multi-bytes characters but not for composing or joining.
 
<syntaxhighlight lang="powershell">
$a = 'abc 🐧 def'
$enum = $a.EnumerateRunes() | % { "$_" }
-join $enum[$enum.length..0] # fed 🐧 cba
</syntaxhighlight>
 
==== For graphemes ====
 
For composing or joining, enumerating graphemes is required.
 
<syntaxhighlight lang="powershell">
$a = "aeiou`u{0308}yz"
$enum = [System.Globalization.StringInfo]::GetTextElementEnumerator($a)
$arr = @()
while($enum.MoveNext()) { $arr += $enum.GetTextElement() }
[array]::reverse($arr)
$arr -join '' # zyüoiea
</syntaxhighlight>
 
=={{header|Prolog}}==
{{works with|SWI Prolog}}
<langsyntaxhighlight lang="prolog">reverse("abcd", L), string_to_list(S,L).</langsyntaxhighlight>
{{Out}}
<pre>
Line 3,261 ⟶ 3,675:
The main workings are hidden inside the reverse/2 predicate,
so lets write one to see how it works:
<langsyntaxhighlight lang="prolog">accRev([H|T], A, R) :- accRev(T, [H|A], R).
accRev([], A, A).
 
rev(L,R) :- accRev(L,[],R).</langsyntaxhighlight>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Debug ReverseString("!dekrow tI")</langsyntaxhighlight>
 
=={{header|Python}}==
===Optimized for user input===
<syntaxhighlight lang ="python">input()[::-1]</langsyntaxhighlight>
 
===Already known string===
<syntaxhighlight lang ="python">string[::-1]</langsyntaxhighlight>
or
<syntaxhighlight lang ="python">''.join(reversed(string))</langsyntaxhighlight>
 
===Python: Unicode reversal===
Line 3,282 ⟶ 3,696:
 
'''Note:''' How this looks may be subject to how the tool you are using to view this page can render Unicode.
<langsyntaxhighlight lang="python">import unicodedata
 
def ureverse(ustring):
Line 3,310 ⟶ 3,724:
ucode = ''.join(chr(int(n[2:], 16)) for n in
'U+0041 U+030A U+0073 U+0074 U+0072 U+006F U+0308 U+006D'.split())
say_rev(ucode)</langsyntaxhighlight>
 
{{out}}
Line 3,320 ⟶ 3,734:
 
If this code is then used:
<langsyntaxhighlight lang="python">ucode = ''.join(chr(int(n[2:], 16)) for n in
'U+006B U+0301 U+0075 U+032D U+006F U+0304 U+0301 U+006E'.split())
say_rev(ucode)</langsyntaxhighlight>
It produces this output
{{out}}
Line 3,332 ⟶ 3,746:
 
'''This uses the unicode string mentioned in the task:'''
<langsyntaxhighlight lang="python">ucode = ''.join(chr(int(n, 16))
for n in ['61', '73', '20dd', '64', '66', '305'])
say_rev(ucode)</langsyntaxhighlight>
It produces this output
{{out}}
Line 3,344 ⟶ 3,758:
=={{header|Quackery}}==
reverse is predefined (and applies to nests in general, including strings) as:
<langsyntaxhighlight Quackerylang="quackery"> [ dup nest? if
[ [] swap witheach
[ nested
swap join ] ] ] is reverse ( x --> x )</langsyntaxhighlight>
 
 
=={{header|Qi}}==
It's simplest just to use the common lisp REVERSE function.
<langsyntaxhighlight Qilang="qi">(REVERSE "ABCD")</langsyntaxhighlight>
 
=={{header|R}}==
{{works with|R|2.8.1}}
The following code works with UTF-8 encoded strings too.
<langsyntaxhighlight Rlang="r">revstring <- function(stringtorev) {
return(
paste(
Line 3,363 ⟶ 3,777:
,collapse="")
)
}</langsyntaxhighlight>
 
Alternatively (using rev() function):
 
<langsyntaxhighlight Rlang="r"> revstring <- function(s) paste(rev(strsplit(s,"")[[1]]),collapse="")</langsyntaxhighlight>
 
<langsyntaxhighlight Rlang="r">revstring("asdf")
revstring("m\u00f8\u00f8se")
Encoding("m\u00f8\u00f8se") # just to check if on your system it's something
# different!</langsyntaxhighlight>
{{out}}
<pre>
Line 3,385 ⟶ 3,799:
As in Scheme:
 
<langsyntaxhighlight Racketlang="racket">#lang racket
 
(define (string-reverse s)
(list->string (reverse (string->list s))))
 
(string-reverse "aoeu")</langsyntaxhighlight>
 
{{out}}
Line 3,402 ⟶ 3,816:
{{Works with|rakudo|2018.08}}
Raku handles graphemes, multi-byte characters and emoji correctly by default.
<syntaxhighlight lang="raku" perl6line>say "hello world".flip;
say "as⃝df̅".flip;
say 'ℵΑΩ 駱駝道 🤔 🇸🇧 🇺🇸 🇬🇧‍ 👨‍👩‍👧‍👦🆗🗺'.flip;</langsyntaxhighlight>
{{out}}
<pre>dlrow olleh
Line 3,411 ⟶ 3,825:
 
=={{header|RapidQ}}==
<syntaxhighlight lang="vb">
<lang vb>
print reverse$("This is a test")
</syntaxhighlight>
</lang>
 
=={{header|Rascal}}==
<langsyntaxhighlight lang="rascal">import String;
reverse("string")</langsyntaxhighlight>
 
=={{header|Raven}}==
<langsyntaxhighlight Ravenlang="raven">"asdf" reverse</langsyntaxhighlight>
{{out}}
<pre>fdsa</pre>
 
=={{header|REBOL}}==
<langsyntaxhighlight REBOLlang="rebol">print reverse "asdf"</langsyntaxhighlight>
Note the string is reversed in place. If you were using it anywhere else, you would find it reversed:
<langsyntaxhighlight REBOLlang="rebol">x: "asdf"
print reverse x
print x ; Now reversed.</langsyntaxhighlight>
REBOL/View 2.7.6.3.1 14-Mar-2008 does not handle Unicode strings. This is planned for REBOL 3.
 
=={{header|Red}}==
<langsyntaxhighlight Redlang="red">>> reverse "asdf"
== "fdsa"</langsyntaxhighlight>
 
=={{header|Refal}}==
<syntaxhighlight lang="refal">$ENTRY Go {
= <Prout <Reverse 'asdf'>>;
};
 
Reverse {
(e.X) = e.X;
(e.X) s.C e.Y = <Reverse (s.C e.X) e.Y>;
e.X = <Reverse () e.X>;
};</syntaxhighlight>
{{out}}
<pre>fdsa</pre>
 
=={{header|ReScript}}==
<langsyntaxhighlight ReScriptlang="rescript">let rev_string = (s) => {
let len = Js.String2.length(s)
let arr = []
Line 3,447 ⟶ 3,874:
}
 
Js.log(rev_string("abcdefg"))</langsyntaxhighlight>
{{out}}
<pre>
Line 3,456 ⟶ 3,883:
 
=={{header|Retro}}==
<syntaxhighlight lang Retro="retro">'asdf s:reverse s:put</langsyntaxhighlight>
 
=={{header|REXX}}==
All methods shown below also work with &nbsp; '''NULL''' &nbsp; values &nbsp; (strings with a zero length).
===using REVERSE BIF===
<langsyntaxhighlight lang="rexx">/*REXX program to reverse a string (and show before and after strings).*/
 
string1 = 'A man, a plan, a canal, Panama!'
Line 3,468 ⟶ 3,895:
say ' original string: ' string1
say ' reversed string: ' string2
/*stick a fork in it, we're done.*/</langsyntaxhighlight>
'''output'''
<pre>
Line 3,476 ⟶ 3,903:
 
===using SUBSTR BIF, left to right===
<langsyntaxhighlight lang="rexx">/*REXX program to reverse a string (and show before and after strings).*/
 
string1 = 'A man, a plan, a canal, Panama!'
Line 3,485 ⟶ 3,912:
say ' original string: ' string1
say ' reversed string: ' string2
/*stick a fork in it, we're done.*/</langsyntaxhighlight>
'''output''' &nbsp; is identical to the 1<sup>st</sup> REXX version.
<br><br>(Regarding the previous example) &nbsp; Another method of coding an abutment (an implied concatenation) is:
<langsyntaxhighlight lang="rexx"> string2 = substr(string1,j,1) || string2
/*───── or ─────*/
string2= substr(string1,j,1)string2</langsyntaxhighlight>
 
===using SUBSTR BIF, right to left===
<langsyntaxhighlight lang="rexx">/*REXX program to reverse a string (and show before and after strings).*/
 
string1 = 'A man, a plan, a canal, Panama!'
Line 3,502 ⟶ 3,929:
say ' original string: ' string1
say ' reversed string: ' string2
/*stick a fork in it, we're done.*/</langsyntaxhighlight>
'''output''' is identical to the 1<sup>st</sup> version.
<br><br>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
cStr = "asdf" cStr2 = ""
for x = len(cStr) to 1 step -1 cStr2 += cStr[x] next
See cStr2 # fdsa
</syntaxhighlight>
</lang>
 
=={{header|RLaB}}==
<langsyntaxhighlight RLaBlang="rlab">>> x = "rosettacode"
rosettacode
 
Line 3,525 ⟶ 3,952:
 
>> rx
edocattesor</langsyntaxhighlight>
 
=={{header|Robotic}}==
<langsyntaxhighlight lang="robotic">
. "local1 = Main string"
. "local2 = Temporary string storage"
Line 3,545 ⟶ 3,972:
* "Reversed string: &$local1& (Length: &$local1.length&)"
end
</syntaxhighlight>
</lang>
 
=={{header|RPL}}==
{{works with|Halcyon Calc|4.2.7}}
≪ ""
OVER SIZE 1 '''FOR''' j
OVER j DUP SUB +
-1 '''STEP''' SWAP DROP
≫ '<span style="color:blue">RVSTR</span>' STO
"ABC" <span style="color:blue">RVSTR</span>
{{out}}
<pre>1: "CBA"</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">str = "asdf"
reversed = str.reverse</lang>
"résumé niño".reverse #=> "oñin émusér"</syntaxhighlight>
or
<lang ruby>#encoding: utf-8
"résumé niño".reverse #=> "oñin émusér"</lang>
for extra credit
<langsyntaxhighlight lang="ruby">
graphemes = 'as⃝df̅'.scan(/\X/)
reversed = graphemes.reverse
graphemes.join #=> "f̅ds⃝a"
</syntaxhighlight>
</lang>
 
=={{header|Run BASIC}}==
{{works with|Just BASIC}}
<lang runbasic>string$ = "123456789abcdefghijk"
{{works with|Liberty BASIC}}
{{works with|QBasic}}
{{works with|Yabasic}}
<syntaxhighlight lang="runbasic">string$ = "123456789abcdefghijk"
for i = len(string$) to 1 step -1
print mid$(string$,i,1);
next i</langsyntaxhighlight>
 
=={{header|Rust}}==
Line 3,570 ⟶ 4,011:
Reversing ASCII byte-slice (in-place):
 
<langsyntaxhighlight lang="rust">let mut buffer = b"abcdef".to_vec();
buffer.reverse();
assert_eq!(buffer, b"fedcba");</langsyntaxhighlight>
 
Reversing Unicode scalar values:
 
<langsyntaxhighlight lang="rust">let output: String = "一二三四五六七八九十".chars().rev().collect();
assert_eq!(output, "十九八七六五四三二一");</langsyntaxhighlight>
 
Reversing a <code>Chars</code> iterator doesn't solve the complete problem, because it iterates unicode scalar values, which doesn't account for combining marks:
 
<langsyntaxhighlight lang="rust">let output: String = "as⃝df̅".chars().rev().collect();
assert_ne!(output, "f̅ds⃝a"); // should be this
assert_eq!(output, "̅fd⃝sa");</langsyntaxhighlight>
 
Reversing graphemes clusters, which is provided by the [https://unicode-rs.github.io/unicode-segmentation/unicode_segmentation/struct.Graphemes.html unicode-segmentation] crate, solves the problem:
 
<langsyntaxhighlight lang="rust">use unicode_segmentation::UnicodeSegmentation;
 
let output: String = "as⃝df̅".graphemes(true).rev().collect();
assert_eq!(output, "f̅ds⃝a");</langsyntaxhighlight>
 
=={{header|S-lang}}==
Here is an 8-bit version:
<langsyntaxhighlight Slang="s-lang">variable sa = "Hello, World", aa = Char_Type[strlen(sa)+1];
init_char_array(aa, sa);
array_reverse(aa);
Line 3,603 ⟶ 4,044:
% onto the array:
print( strjoin(array_map(String_Type, &char, aa), "") );</langsyntaxhighlight>
 
Output: "dlroW ,olleH"
Line 3,610 ⟶ 4,051:
Side note: If needed, strbytelen() would give total length of string.
 
<langsyntaxhighlight Slang="s-lang">define init_unicode_array(a, buf)
{
variable len = strbytelen(buf), ch, p0 = 0, p1 = 0;
Line 3,626 ⟶ 4,067:
array_reverse(au);
% print(au);
print(strjoin(array_map(String_Type, &char, au), "") );</langsyntaxhighlight>
 
Output: "ηψόκ νὴτ ὸπἀ ωζίρωνγ ὲΣ"
Line 3,634 ⟶ 4,075:
 
=={{header|SAS}}==
<langsyntaxhighlight lang="sas">data _null_;
length a b $11;
a="I am Legend";
Line 3,640 ⟶ 4,081:
put a;
put b;
run;</langsyntaxhighlight>
 
=={{header|Sather}}==
<langsyntaxhighlight lang="sather">class MAIN is
main is
s ::= "asdf";
Line 3,649 ⟶ 4,090:
-- current implementation does not handle multibyte encodings correctly
end;
end;</langsyntaxhighlight>
 
=={{header|Scala}}==
Easy way:
<langsyntaxhighlight lang="scala">"asdf".reverse</langsyntaxhighlight>
 
Slightly less easy way:
<langsyntaxhighlight lang="scala">"asdf".foldRight("")((a,b) => b+a)</langsyntaxhighlight>
 
Unicode-aware, method 1:
 
<langsyntaxhighlight lang="scala">def reverse(s: String) = {
import java.text.{Normalizer,BreakIterator}
val norm = Normalizer.normalize(s, Normalizer.Form.NFKC) // waffle -> waffle (optional)
Line 3,670 ⟶ 4,111:
}
break(it, it.first).mkString
}</langsyntaxhighlight>
{{out}}
<pre>scala> reverse("as⃝df̅")
Line 3,676 ⟶ 4,117:
 
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.
<langsyntaxhighlight lang="scala">def reverseString(s: String) = {
import java.lang.Character._
Line 3,705 ⟶ 4,146:
}
recurse(splitString(s), Nil)
}</langsyntaxhighlight>
REPL on Windows doesn't handle Unicode, so I'll show the bytes instead:
<pre>
Line 3,716 ⟶ 4,157:
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">(define (string-reverse s)
(list->string (reverse (string->list s))))</langsyntaxhighlight>
 
> (string-reverse "asdf")
Line 3,726 ⟶ 4,167:
 
=={{header|Sed}}==
<langsyntaxhighlight lang="sed">#!/bin/sed -f
 
/../! b
Line 3,743 ⟶ 4,184:
 
# Remove the newline markers
s/\n//g</langsyntaxhighlight>
 
=={{header|Seed7}}==
Seed7 strings are encoded with UTF-32 therefore no special Unicode solution is necessary. The following demonstrates one way of reversing a string with a user-defined function.
<syntaxhighlight lang="ada" seed7line="1">$ include "seed7_05.s7i";
 
const func string: reverse reverso(in string: stri) is func
result
var string: result is "";
Line 3,762 ⟶ 4,203:
const proc: main is func
begin
writeln(reversereverso("Was it a cat I saw"));
end func;</syntaxhighlight>The following demonstrates the use of the built-in 'reverse' function:<syntaxhighlight lang="ada" line="1">
end func;</lang>
$ include "seed7_05.s7i";
{{out}}
 
const proc: main is func
begin
writeln(reverse("Was it a cat I saw?"));
end func;
</syntaxhighlight>{{out}}
<pre>
was I tac a ti saW
Line 3,771 ⟶ 4,218:
=={{header|Self}}==
In-place reversal:
<syntaxhighlight lang ="self">'asdf' copyMutable reverse</langsyntaxhighlight>
 
=={{header|SenseTalk}}==
<langsyntaxhighlight lang="sensetalk">put "asdf" reversed -- reverse on the fly
 
set imp to "rumpelstiltskin"
reverse imp -- reverse in place
put imp
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,790 ⟶ 4,237:
 
There is a library function to reverse any Sequence. This works for strings since strings are Sequences of characters.
<langsyntaxhighlight lang="sequencel">import <Utilities/Sequence.sl>;
 
main(args(2)) := Sequence::reverse(args[1]);</langsyntaxhighlight>
 
'''The Library Function:'''
 
The following is the library implementation of the reverse function.
<langsyntaxhighlight lang="sequencel">reverse<T> : T(1) -> T(1);
reverse(list(1))[i] :=
let
range := - ((1 ... size(list)) - (size(list) + 1));
in
list[i] foreach i within range;</langsyntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">"asdf".reverse; # fdsa
"résumé niño".reverse; # oñin émusér</langsyntaxhighlight>
 
=={{header|Simula}}==
<langsyntaxhighlight lang="simula">
BEGIN
TEXT PROCEDURE REV(S); TEXT S;
Line 3,836 ⟶ 4,283:
OUTTEXT(REV(INP)); OUTIMAGE;
END
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,845 ⟶ 4,292:
=={{header|Slate}}==
In-place reversal:
<syntaxhighlight lang ="slate">'asdf' reverse</langsyntaxhighlight>
Non-destructive reversal:
<syntaxhighlight lang ="slate">'asdf' reversed</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
<syntaxhighlight lang ="smalltalk">'asdf' reverse</langsyntaxhighlight>
{{works with|Smalltalk/X}}
the above does inplace, destructive reverse. It is usually better to use
<syntaxhighlight lang ="smalltalk">'asdf' reversed</langsyntaxhighlight>
which returns a new string.
 
=={{header|SNOBOL4}}==
ASCII-only
<langsyntaxhighlight lang="snobol"> output = reverse(reverse("reverse"))
end</langsyntaxhighlight>
{{out}}
<pre>reverse</pre>
 
=={{header|Standard ML}}==
<langsyntaxhighlight lang="sml">val str_reverse = implode o rev o explode;
val string = "asdf";
val reversed = str_reverse string;</langsyntaxhighlight>
 
=={{header|Stata}}==
Line 3,872 ⟶ 4,319:
Use '''[https://www.stata.com/help.cgi?f_strreverse strreverse]''' if there are only ASCII characters, and '''[https://www.stata.com/help.cgi?f_ustrreverse ustrreverse]''' if there are Unicode characters in the string.
 
<langsyntaxhighlight lang="stata">. scalar s="ARS LONGA VITA BREVIS"
. di strreverse(s)
SIVERB ATIV AGNOL SRA
. scalar s="Ἐν ἀρχῇ ἐποίησεν ὁ θεὸς τὸν οὐρανὸν καὶ τὴν γῆν"
. di ustrreverse(s)
νῆγ νὴτ ὶακ νὸναρὐο νὸτ ςὸεθ ὁ νεσηίοπἐ ῇχρἀ νἘ</langsyntaxhighlight>
 
=={{header|Stringle}}==
This inputs a string from the user and outputs its reverse. The <code>\</code> ''reverse'' operator reverses any string.
 
<syntaxhighlight lang="stringle">$ \$</syntaxhighlight>
 
=={{header|Swift}}==
Swift's strings are iterated by <code>Character</code>s, which represent "Unicode grapheme clusters", so reversing it reverses it with combining characters too:
{{works with|Swift|2.x+}}
<langsyntaxhighlight lang="swift">func reverseString(s: String) -> String {
return String(s.characters.reverse())
}
print(reverseString("asdf"))
print(reverseString("as⃝df̅"))</langsyntaxhighlight>
{{works with|Swift|1.x}}
<langsyntaxhighlight lang="swift">func reverseString(s: String) -> String {
return String(reverse(s))
}
println(reverseString("asdf"))
println(reverseString("as⃝df̅"))</langsyntaxhighlight>
{{out}}
<pre>
Line 3,902 ⟶ 4,354:
 
=={{header|Symsyn}}==
<syntaxhighlight lang="symsyn">
<lang Symsyn>
| reverse string
 
Line 3,921 ⟶ 4,373:
endif
c []
</syntaxhighlight>
</lang>
OR
 
<syntaxhighlight lang="symsyn">
<lang Symsyn>
c : 'abcdefghijklmnopqrstuvwxyz'
 
Line 3,937 ⟶ 4,389:
endif
$s []
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,946 ⟶ 4,398:
 
=={{header|Tailspin}}==
<langsyntaxhighlight lang="tailspin">
templates reverse
'$:[ $... ] -> $(last..first:-1)...;' !
Line 3,957 ⟶ 4,409:
'as⃝df̅' -> reverse -> !OUT::write
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,965 ⟶ 4,417:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
string reverse asdf</langsyntaxhighlight>
 
=={{header|TI-83 BASIC}}==
Note: length( and sub( can be found in the catalog.
<langsyntaxhighlight lang="ti83b">:Str1
:For(I,1,length(Ans)-1
:sub(Ans,2I,1)+Ans
:End
:sub(Ans,1,I→Str1</langsyntaxhighlight>
 
=={{header|TMG}}==
Unix TMG:
<langsyntaxhighlight UnixTMGlang="unixtmg">prog: parse(str);
str: smark any(!<<>>) scopy str/done = { 1 2 };
done: ;</langsyntaxhighlight>
 
=={{header|Tosh}}==
<langsyntaxhighlight Toshlang="tosh">when flag clicked
ask "Say something..." and wait
set i to (length of answer)
Line 3,991 ⟶ 4,443:
change i by -1
end
say inv</langsyntaxhighlight>
 
=={{header|Transd}}==
<syntaxhighlight lang="scheme">#lang transd
 
MainModule : {
_start: (lambda (with s "as⃝df̅"
(textout (reverse s))
 
// reversing user input
(textout "\nPlease, enter a string: ")
(textout "Input: " (reverse (read s)))
))
}</syntaxhighlight>
{{out}}
<pre>
̅fd⃝sa
Please, enter a string: Hello!
Input: !olleH
</pre>
 
=={{header|Turing}}==
Iterative solution, for character shovelers:
 
<langsyntaxhighlight Turinglang="turing">function reverse (s : string) : string
var rs := ""
for i : 0 .. length (s) - 1
Line 4,005 ⟶ 4,476:
 
put reverse ("iterative example")
put reverse (reverse ("iterative example"))</langsyntaxhighlight>
 
{{out}}
Line 4,015 ⟶ 4,486:
Recursive solution, more natural in Turing:
 
<langsyntaxhighlight Turinglang="turing">function reverse (s : string) : string
if s = "" then
result s
Line 4,024 ⟶ 4,495:
 
put reverse ("recursive example")
put reverse (reverse ("recursive example"))</langsyntaxhighlight>
 
{{out}}
Line 4,033 ⟶ 4,504:
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight 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</langsyntaxhighlight>
{{out}}
<pre>
Line 4,045 ⟶ 4,516:
 
=={{header|UNIX Shell}}==
<langsyntaxhighlight lang="bash">
#!/bin/bash
str=abcde
Line 4,052 ⟶ 4,523:
 
echo $rev
</syntaxhighlight>
</lang>
 
'''or'''
 
<langsyntaxhighlight lang="bash">
str='i43go1342iu 23iu4o 23iu14i324y 2i13'
rev <<< "$str"
#rev is not built-in function, though is in /usr/bin/rev
</syntaxhighlight>
</lang>
 
=={{header|Unlambda}}==
Reverse the whole input:
<langsyntaxhighlight Unlambdalang="unlambda">``@c`d``s`|k`@c</langsyntaxhighlight>
 
=={{header|Ursala}}==
<langsyntaxhighlight Ursalalang="ursala">#import std
 
#cast %s
Line 4,073 ⟶ 4,544:
example = ~&x 'asdf'
 
verbose_example = reverse 'asdf'</langsyntaxhighlight>
{{out}}
<pre>
Line 4,080 ⟶ 4,551:
 
=={{header|Vala}}==
<langsyntaxhighlight lang="vala">int main (string[] args) {
if (args.length < 2) {
stdout.printf ("Please, input a string.\n");
Line 4,091 ⟶ 4,562:
stdout.printf ("%s\n", str.str.strip ().reverse ());
return 0;
}</langsyntaxhighlight>
 
=={{header|VBA}}==
===Non-recursive version===
<langsyntaxhighlight VBAlang="vba">Public Function Reverse(aString as String) as String
' returns the reversed string
dim L as integer 'length of string
Line 4,106 ⟶ 4,577:
next
Reverse = newString
End Function</langsyntaxhighlight>
===Recursive version===
<langsyntaxhighlight VBAlang="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
Line 4,121 ⟶ 4,592:
RReverse = RReverse(Right$(aString, L - M)) & RReverse(Left$(aString, M))
End If
End Function</langsyntaxhighlight>
===Example dialogue===
<pre>
Line 4,136 ⟶ 4,607:
=={{header|VBScript}}==
{{works with|Windows Script Host|*}}
<syntaxhighlight lang="vbscript">
<lang VBScript>
WScript.Echo StrReverse("asdf")
</syntaxhighlight>
</lang>
 
=={{header|Vedit macro language}}==
This routine reads the text from current line, reverses it and stores the reversed string in text register 10:
<langsyntaxhighlight lang="vedit">Reg_Empty(10)
for (BOL; !At_EOL; Char) {
Reg_Copy_Block(10, CP, CP+1, INSERT)
}</langsyntaxhighlight>
This routine reverses the current line in-place:
<langsyntaxhighlight lang="vedit">BOL
while (!At_EOL) {
Block_Copy(EOL_pos-1, EOL_pos, DELETE)
}</langsyntaxhighlight>
 
=={{header|Visual Basic}}==
{{works with|Visual Basic|6}}
<langsyntaxhighlight lang="vb">Debug.Print VBA.StrReverse("Visual Basic")</langsyntaxhighlight>
 
=={{header|Visual Basic .NET}}==
Line 4,163 ⟶ 4,634:
Since the windows console may not support Unicode, the program can optionally redirect its output to a file.
 
<langsyntaxhighlight lang="vbnet">#Const REDIRECTOUT = True
 
Module Program
Line 4,219 ⟶ 4,690:
#End If
End Sub
End Module</langsyntaxhighlight>
 
{{out|note=copied from Notepad}}
Line 4,236 ⟶ 4,707:
 
=={{header|Wart}}==
<langsyntaxhighlight lang="wart">(rev "asdf")</langsyntaxhighlight>
 
Wart doesn't support Unicode yet.
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">const list =
('
Hello world!
你好世界!
Salamu, Dunia!
こんにちは世界!
¡Hola Mundo!
Chào thế giới!
Hallo Welt!
')
 
fn main() {
for line in list.split('\n') {if line !='' {println(reverse_string(line))}}
}
 
fn reverse_string(word string) string {
return word.runes().reverse().string()
}</syntaxhighlight>
 
{{out}}
<pre>
!dlrow olleH
!界世好你
!ainuD ,umalaS
!界世はちにんこ
!odnuM aloH¡
!iớig ếht oàhC
!tleW ollaH
</pre>
 
=={{header|Wren}}==
{{libheader|Wren-str}}
{{libheader|Wren-upc}}
<langsyntaxhighlight ecmascriptlang="wren">import "./str" for Str
import "./upc" for Graphemes
 
for (word in ["asdf", "josé", "møøse", "was it a car or a cat I saw", "😀🚂🦊"]) {
Line 4,252 ⟶ 4,754:
for (word in ["as⃝df̅", "ℵΑΩ 駱駝道 🤔 🇸🇧 🇺🇸 🇬🇧‍ 👨‍👩‍👧‍👦🆗🗺"]) {
System.print(Graphemes.new(word).toList[-1..0].join())
}</langsyntaxhighlight>
 
{{out}}
Line 4,266 ⟶ 4,768:
 
=={{header|Wortel}}==
<langsyntaxhighlight lang="wortel">; the @rev operator reverses strings and arrays
@rev "abc" ; returns "cba"
; or the same thing using a pointer expression
!~r "abc"</langsyntaxhighlight>
 
=={{header|XBS}}==
Using the standard library
<langsyntaxhighlight XBSlang="xbs">log(string.reverse("Hello"))</langsyntaxhighlight>
{{out}}
<pre>
Line 4,279 ⟶ 4,781:
</pre>
Using [[JavaScript]] methods
<langsyntaxhighlight XBSlang="xbs">log("Hello"->split("")->reverse()->join(""));</langsyntaxhighlight>
{{out}}
<pre>
Line 4,285 ⟶ 4,787:
</pre>
Using a custom method
<langsyntaxhighlight XBSlang="xbs">func ReverseString(String){
set Final = "";
for(i=?String-1;0;-1){
Line 4,292 ⟶ 4,794:
send Final;
}
log(ReverseString("Hello"));</langsyntaxhighlight>
{{out}}
<pre>
Line 4,299 ⟶ 4,801:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
string 0; \use zero-terminated strings, instead of MSb terminated
 
Line 4,321 ⟶ 4,823:
Text(0, RevStr("abc")); CrLf(0);
Text(0, RevStr("Able was I ere I saw Elba.")); CrLf(0);
]</langsyntaxhighlight>
 
Output:
Line 4,333 ⟶ 4,835:
=={{header|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.
<langsyntaxhighlight lang="yorick">strchar(strchar("asdf")(:-1)(::-1))</langsyntaxhighlight>
 
=={{header|Z80 Assembly}}==
This method uses the stack as a temporary store to reverse the order of characters in a string, and self-modifying code to restore the loop counter.
 
<langsyntaxhighlight lang="z80">PrintChar equ $BB5A ;Amstrad CPC bios call
Terminator equ 0 ;null terminator for strings
 
Line 4,402 ⟶ 4,904:
djnz LOOP_REVERSESTRING_POP
pop de
ret</langsyntaxhighlight>
 
{{out}}
Line 4,429 ⟶ 4,931:
 
=={{header|Zoea}}==
<syntaxhighlight lang="zoea">
<lang Zoea>
program: reverse_string
input: xyzzy
output: yzzyx
</syntaxhighlight>
</lang>
 
=={{header|Zoea Visual}}==
[http://zoea.co.uk/examples/zv-rc/Reverse_string.png Reverse string]
 
=={{header|Zig}}==
We can use `.*` to dereference a literal string pointer to an array, and use `std.mem.reverse` to reverse the slice of that array in-place:
<syntaxhighlight lang="zig">
var s = "socat".*;
std.mem.reverse(u8, &s);
</syntaxhighlight>
or:
<syntaxhighlight lang="zig">
var s = "socat".*;
std.mem.reverse(u8, s[0..]);
</syntaxhighlight>
String `s` now becomes `"tacos"`.
Tested on version 0.9.0. Reference: [https://ziglang.org/documentation/0.9.0/#String-Literals-and-Unicode-Code-Point-Literals].
3,044

edits