Reverse a string: Difference between revisions
Content deleted Content added
→Nu: add |
|||
(41 intermediate revisions by 19 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,192 ⟶ 1,219:
end;</syntaxhighlight>
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,222 ⟶ 1,280:
return accum "" for i in (0..!(string.size())).descending() { _ + string[i] }
}</syntaxhighlight>
=={{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|EchoLisp}}==
Line 1,314 ⟶ 1,386:
=={{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,659 ⟶ 1,716:
<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,073 ⟶ 2,139:
=={{header|Io}}==
<syntaxhighlight lang="io">"asdf" reverse</syntaxhighlight>
=={{Header|Insitux}}==
<syntaxhighlight lang="insitux">
(reverse "hello")
</syntaxhighlight>
=={{header|J}}==
Line 2,090 ⟶ 2,162:
=={{header|Java}}==
=== Reverse Unicode Codepoints ===
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.
<syntaxhighlight lang="java">
String reversed = new StringBuilder("as⃝df̅").reverse().toString(); // fd⃝sa
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}}==
=== 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,114 ⟶ 2,235:
// 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,244 ⟶ 2,383:
=={{header|langur}}==
<syntaxhighlight lang="langur">writeln
{{out}}
Line 2,529 ⟶ 2,668:
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}}==
Line 2,625 ⟶ 2,792:
puts reverse('reversed')</syntaxhighlight>
=={{header|Miranda}}==
<syntaxhighlight lang="miranda">main :: [sys_message]
main = [Stdout (reverse "esreveR"),
Stdout "\n"]</syntaxhighlight>
{{out}}
<pre>Reverse</pre>
=={{header|Modula-2}}==
Line 2,826 ⟶ 3,000:
=={{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 2,891 ⟶ 3,027:
60 PRINT REVERSED$</syntaxhighlight>
=={{header|
<syntaxhighlight lang="nu">'äsdf' | str reverse</syntaxhighlight>
{{out}}
<pre>fdsä</pre>
=={{header|Oberon-2}}==
Tested with [https://miasap.se/obnc OBNC].
<syntaxhighlight lang="oberon">MODULE reverse;
Line 3,057 ⟶ 3,198:
; ==> !λ ,olleH
</syntaxhighlight>
=={{header|OmniMark}}==
This handles the characters U+0073,U+20DD (Latin Small Letter S + Combining Enclosing Circle; UTF-8: 73 + e2 83 9D) and U+0066,U+0305 (Latin Small Letter F + Combining Overline; UTF-8: 66 + cc 85). It would need extension to handle ''non-combining'' UTF-8 characters, but that's not been done.
<syntaxhighlight lang="omnimark">
macro utf8-not-ascii is
(["%16r{C0}" to "%16r{DF}"] ["%16r{80}" to "%16r{BF}"] |
["%16r{E0}" to "%16r{EF}"] ["%16r{80}" to "%16r{BF}"] {2} |
["%16r{F0}" to "%16r{F7}"] ["%16r{80}" to "%16r{BF}"] {3}) macro-end
global stream reverse initial {''}
process
submit 'as⃝df̅'
find (any-text utf8-not-ascii) => char
set reverse to char || reverse
find any-text => char
set reverse to char || reverse
process-end
output reverse || '%n'
</syntaxhighlight>
{{out}}
<pre>
f̅ds⃝a
</pre>
=={{header|OOC}}==
Line 3,267 ⟶ 3,436:
end;
end;</syntaxhighlight>
=={{header|PascalABC.NET}}==
<syntaxhighlight lang="delphi">
##
var s:='asdf';//ReadLnString;
ReverseString(s).Print;
</syntaxhighlight>
{{out}}
<pre>
fdsa
</pre>
=={{header|Peloton}}==
Line 3,341 ⟶ 3,524:
=== 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,351 ⟶ 3,536:
<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,447 ⟶ 3,660:
=={{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,457 ⟶ 3,673:
{{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,470 ⟶ 3,686:
<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,656 ⟶ 3,897:
<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,770 ⟶ 4,024:
=={{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 3,979 ⟶ 4,235:
=={{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 3,995 ⟶ 4,251:
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,111 ⟶ 4,373:
. 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,403 ⟶ 4,670:
Block_Copy(EOL_pos-1, EOL_pos, DELETE)
}</syntaxhighlight>
=={{header|Vim Script}}==
Take a buffer with the following content:
# Lines 1 and 2, the strings to reverse
# Line 3, comment
# Lines 4 to 6, the Vim Script function
# Lines 7 and 8, calling the Vim Script function twice, in the first instance using line 1's content for the argument and in the second instance line 2's content.
# Line 9, comment
<pre>
asdf
as⃝df̅
""""""""""""""""""""""""
function Reverse(chars)
call append(line('$'),join(reverse(split(a:chars, '\zs')), ""))
endfunction
call Reverse(getline(1))
call Reverse(getline(2))
""""""""""""""""""""""""
</pre>
On entering ''':''' (Command-line mode), then typing '''4,8so''' (and {Enter}), the function and two call commands will be sourced and executed. Output is appended to the end of the buffer at lines 10 and 11.
{{out}}
<pre>
fdsa
f̅ds⃝a
</pre>
This illustrates reversing the simple ASCII text string as well as the one with Unicode combining characters ― the latter keeping s+combining enclosing circle (U+0073,U+20DD) together and f+macron (U+0066,U+0305) together.
=={{header|Visual Basic}}==
Line 4,526 ⟶ 4,823:
{{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", "😀🚂🦊"]) {
|