Idiom #41 Reverse a string
Create the string t containing the same characters as the string s, in reverse order.
The original string s must remain unaltered. Each character must be handled correctly regardless its number of bytes in memory.

- C
- Clojure
- Clojure
- Cobol
- C#
- C#
- D
- Dart
- Dart
- Elixir
- Erlang
- Fortran
- Go
- Go
- Go
- Haskell
- JS
- Java
- Java
- Java
- Java
- Kotlin
- Lisp
- Lua
- Obj-C
- PHP
- Pascal
- Pascal
- Perl
- Python
- Python
- Ruby
- Rust
- Rust
- Scala
- Scheme
- Smalltalk
- VB
(let [s "hello"
t (apply str (reverse s))]
t)
Strings are treated as sequential collections of characters. reverse returns the character list in reverse order, and apply takes this collection and feeds it as arguments into str to return a full reversed string.
As Clojure data structures are immutable, we can guarantee that s is unaltered.
As Clojure data structures are immutable, we can guarantee that s is unaltered.
var t = new String.fromCharCodes(s.runes.toList().reversed);
This does reverse the order of the runes, however it may handle improperly some dependant runes like diacritics.
func reverse(s string) string {
if len(s) <= 1 {
return s
}
var b strings.Builder
b.Grow(len(s))
for len(s) > 0 {
r, l := utf8.DecodeLastRuneInString(s)
s = s[:len(s)-l]
b.WriteRune(r)
}
return b.String()
}
This version of reverse takes care of multi-byte runes, but performs a single allocation.
String t = new StringBuilder(s).reverse().toString();
StringBuilder is available since Java 1.5
String t = s.chars()
.mapToObj(x -> valueOf((char) x))
.reduce((a, b) -> b + a)
.get();
function utf8.reverse(s)
local r = ""
for p,c in utf8.codes(s) do
r = utf8.char(c)..r
end
return r
end
t = utf8.reverse(s)
if string s is an ascii string you can directly use string.reverse instead.
You will also need Lua5.3 or an utf8 module
You will also need Lua5.3 or an utf8 module
my $s = 'cafe' . "\N{COMBINING ACUTE ACCENT}";
my $t = join '', reverse $s =~ /\X/g;
Bet your programming language is not Unicode compliant. Perl, in general, is. Sad state of affairs: https://www.azabani.com/pages/gbu/
As of 2019-09-29, all other solutions are wrong AFAICT with respect to Unicode marks. (Dart has a disclaimer.)
Correct result: "e\N{U+0301}fac"
Wrong result: "\N{U+0301}efac"
As of 2019-09-29, all other solutions are wrong AFAICT with respect to Unicode marks. (Dart has a disclaimer.)
Correct result: "e\N{U+0301}fac"
Wrong result: "\N{U+0301}efac"