Reverse a string: Difference between revisions

m
→‎{{header|Oberon}}: Fixed language name
(→‎Reverse Unicode Graphemes: add code example)
m (→‎{{header|Oberon}}: Fixed language name)
 
(26 intermediate revisions by 15 users not shown)
Line 436:
<syntaxhighlight lang="applescript">{{"! ereht olleH", {5, 4, 3, 2, 1}},
{"! ereht olleH", {5, 4, 3, 2, 1}}}</syntaxhighlight>
 
=={{header|Applesoft BASIC}}==
<syntaxhighlight 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</syntaxhighlight>
 
=={{header|Arturo}}==
Line 564 ⟶ 551:
 
=={{header|BASIC}}==
 
{{works with|QBasic|1.1}}
==={{header|Applesoft BASIC}}===
{{works with|QuickBasic|4.5}}
<syntaxhighlight lang="qbasicapplesoftbasic">function10 reverseA$(a$) = "THE FIVE BOXING WIZARDS JUMP QUICKLY"
20 GOSUB 100REVERSE
b$ = ""
30 PRINT R$
for i = 1 to len(a$)
40 END
b$ = mid$(a$, i, 1) + b$
 
next i
100 REMREVERSE A$
reverse$ = b$
110 R$ = ""
end function</syntaxhighlight>
120 FOR I = 1 TO LEN(A$)
130 R$ = MID$(A$, I, 1) + R$
140 NEXT I
150 RETURN</syntaxhighlight>
 
==={{header|BASIC256}}===
Line 588 ⟶ 579:
{{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}}===
Line 596 ⟶ 606:
150 NEXT
160 PRINT REV$</syntaxhighlight>
 
==={{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}}===
Line 727 ⟶ 748:
 
<syntaxhighlight lang="befunge">55+~>:48>*#8\#4`#:!#<#~_$>:#,_@</syntaxhighlight>
 
=={{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}}==
Line 1,220 ⟶ 1,247:
{{out}}
<pre>Hello, world!</pre>
 
=={{header|dt}}==
<syntaxhighlight lang="dt">"asdf" rev</syntaxhighlight>
 
=={{header|DWScript}}==
Line 1,243 ⟶ 1,273:
{{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}}==
Line 1,342 ⟶ 1,385:
 
=={{header|Elm}}==
<syntaxhighlight lang="elm">--module TheMain import on the next line provides the reverse stringexposing (main)
-- 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")
]</syntaxhighlight>
 
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}}==
Line 1,687 ⟶ 1,715:
<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>
 
Line 2,101 ⟶ 2,138:
=={{header|Io}}==
<syntaxhighlight lang="io">"asdf" reverse</syntaxhighlight>
 
=={{Header|Insitux}}==
 
<syntaxhighlight lang="insitux">
(reverse "hello")
</syntaxhighlight>
 
=={{header|J}}==
Line 2,176 ⟶ 2,219:
 
=== 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.
Line 2,189 ⟶ 2,234:
// 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>
 
Line 2,319 ⟶ 2,382:
 
=={{header|langur}}==
ThisThe accountsreverse() forfunction codewill points,reverse buta notstring foraccording to graphemes.
<syntaxhighlight lang="langur">writeln cp2s reverse s2cp q("don't you know)"</syntaxhighlight>
 
{{out}}
Line 2,936 ⟶ 2,999:
 
=={{header|Nim}}==
<syntaxhighlight 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)</syntaxhighlight>
{{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:
 
<syntaxhighlight lang="nim">import unicode
 
doAssert "foobar".reversed == "raboof"
doAssert "先秦兩漢".reversed == "漢兩秦先"</syntaxhighlight>
 
=={{header|NS-HUBASIC}}==
Line 3,001 ⟶ 3,026:
60 PRINT REVERSED$</syntaxhighlight>
 
=={{header|Oberon-2}}==
Tested with [https://miasap.se/obnc OBNC].
<syntaxhighlight lang="oberon">MODULE reverse;
Line 3,451 ⟶ 3,476:
 
=== 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>.
Line 3,461 ⟶ 3,488:
 
<syntaxhighlight lang="php">
implode('', array_reverse(mb_str_split($string))); // fed 🐧 cba
</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>
 
Line 3,557 ⟶ 3,612:
 
=={{header|PowerShell}}==
 
=== For ASCII ===
 
Test string
<syntaxhighlight lang="powershell">$s = "asdf"</syntaxhighlight>
====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}}
Line 3,567 ⟶ 3,625:
{{works with|PowerShell|2}}
<syntaxhighlight lang="powershell">[array]::Reverse($s)</syntaxhighlight>
====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}}
Line 3,580 ⟶ 3,638:
<syntaxhighlight lang="powershell">
[Regex]::Matches($s,'.','RightToLeft').Value -join ''
</syntaxhighlight>
 
=== For Unicode ===
 
==== For codepoints ====
 
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>
 
Line 3,766 ⟶ 3,849:
<syntaxhighlight lang="red">>> reverse "asdf"
== "fdsa"</syntaxhighlight>
 
=={{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}}==
Line 3,880 ⟶ 3,976:
=={{header|RPL}}==
{{works with|Halcyon Calc|4.2.7}}
→ str""
"" strOVER SIZE 1 '''FOR''' j str j DUP SUB + -1 '''STEP'''
OVER j DUP SUB +
≫ ≫ 'RVSTR' STO
-1 '''STEP''' SWAP DROP
≫ '<span style="color:blue">RVSTR</span>' STO
"ABC" <span style="color:blue">RVSTR</span>
{{out}}
<pre>1: "CBA"</pre>
Line 4,089 ⟶ 4,187:
 
=={{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="seed7ada" line="1">$ include "seed7_05.s7i";
 
const func string: reverse reverso(in string: stri) is func
result
var string: result is "";
Line 4,105 ⟶ 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">
$ 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 4,221 ⟶ 4,325:
. di ustrreverse(s)
νῆγ νὴτ ὶακ νὸναρὐο νὸτ ςὸεθ ὁ νεσηίοπἐ ῇχρἀ νἘ</syntaxhighlight>
 
=={{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}}==
Line 4,636 ⟶ 4,745:
{{libheader|Wren-str}}
{{libheader|Wren-upc}}
<syntaxhighlight lang="ecmascriptwren">import "./str" for Str
import "./upc" for Graphemes
 
for (word in ["asdf", "josé", "møøse", "was it a car or a cat I saw", "😀🚂🦊"]) {
3,032

edits