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|Arturo}}==
Line 564 ⟶ 551:
=={{header|BASIC}}==
==={{header|Applesoft BASIC}}===
<syntaxhighlight lang="
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|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">
import Html exposing (Html, text, div, p)
import Html.Attributes exposing (style)
change myText =
text ("reverse " ++ myText
++ " = " ++ String.reverse myText)
main =
div [style "margin" "5%", style "font-size" "1.5em"]
[change "as⃝da"
, p []
,
]
</syntaxhighlight>
Link to live demo:
{{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}}==
<syntaxhighlight lang="langur">writeln
{{out}}
Line 2,936 ⟶ 2,999:
=={{header|Nim}}==
=== Unicode codepoints ===
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...
Hence:
<syntaxhighlight lang="nim">
import unicode
doAssert "foobar".reversed == "raboof"
doAssert "先秦兩漢".reversed == "漢兩秦先"
</syntaxhighlight>
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.
=== Unicode graphemes ===
There is no native method to handle grapheme currently.
=={{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)));
</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('👦🏻👋', '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}}
≪
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>
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="
const func string:
result
var string: result is "";
Line 4,105 ⟶ 4,203:
const proc: main is func
begin
writeln(
end func;</syntaxhighlight>The following demonstrates the use of the built-in 'reverse' function:<syntaxhighlight lang="ada" line="1">
$ include "seed7_05.s7i";
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="
import "./upc" for Graphemes
for (word in ["asdf", "josé", "møøse", "was it a car or a cat I saw", "😀🚂🦊"]) {
|