Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Go

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"
import (
  "strings"
  "unicode/utf8"
)
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.
runes := []rune(s)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
   runes[i], runes[j] = runes[j], runes[i]
}
t := string(runes)

This takes care of multi-byte runes, which count as a single character.
import "slices"
runes := []rune(s)
slices.Reverse(runes)
t := string(runes)

Since Go 1.21
#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