Logo

Programming-Idioms

  • Clojure
  • Dart
  • Rust
  • Haskell

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.

Turning the string "café" into "éfac"
t = reverse s :: String
(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.
(require '[clojure.string :as str])
(def t (str/reverse s))
var t = s.split('').reversed.join();

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.
let t: String = s.chars().rev().collect();
let t = s.chars().rev().collect::<String>();

collect is a function with a generic return type, so we must explicitly specify that we want a String back, either by annotating t's type as a String, or by specifying with the so-called "turbofish" syntax.
#include <stdlib.h>
#include <string.h>
char *strrev(char *s)
{
	size_t len = strlen(s);
	char *rev = malloc(len + 1);

	if (rev) {
		char *p_s = s + len - 1;
		char *p_r = rev;

		for (; len > 0; len--)
			*p_r++ = *p_s--;
		*p_r = '\0';
	}
	return rev;
}

Returns NULL on failure

New implementation...
< >
programming-idioms.org