Taskcore
Reverse a string
Also called reverse the characters of a string, reverse a string by code points, reverse a string by grapheme clusters.
Reverse the code points of a string without breaking UTF-8 or UTF-16, and reverse its grapheme clusters where the standard library can find them.
- Evidence
- Code in 10 languages
Task
Reverse the order of the characters in a string. The word "character" can mean four different things, and each one gives a different result.
- A byte is one unit of UTF-8. A code point takes 1 to 4 bytes in UTF-8.
- A UTF-16 code unit is one unit of a Java, JavaScript or C# string. A code point above U+FFFF takes two units: a high surrogate followed by a low surrogate. This is a surrogate pair.
- A code point is one Unicode scalar value, such as U+0065 for
eor U+1F642 for π. - A grapheme cluster is what a reader sees as one character. UAX #29 defines the extended grapheme cluster. One cluster can hold many code points: a letter and its combining marks, a flag made of two regional indicators, or emoji joined by U+200D ZERO WIDTH JOINER.
The main entry, reverse_code_points(s), reverses the code points. Each code point keeps its bytes or its units in their order. So the result has the same length as s in bytes, in units and in code points.
The second entry, reverse_graphemes(s), reverses the extended grapheme clusters. The JavaScript, TypeScript, Java and C# solutions have it, because their standard libraries find grapheme boundaries. The Rust standard library does not provide grapheme iteration. This page uses only the standard library, so the other solutions reverse code points only.
In C, C++, Go and Bash a string can hold any bytes. There the solution checks that the bytes are valid UTF-8. If they are not, it reports an error and returns no result.
Solutions
- Python.
s[::-1]. Astris a sequence of code points, so a slice with step -1 reverses the code points. - JavaScript and TypeScript.
[...s].reverse().join(""). The spread syntax uses the string iterator, which yields code points and keeps each surrogate pair together. For graphemes,Intl.Segmenterwithgranularity: "grapheme"splits the string at grapheme cluster boundaries, and the code reverses the segments. The TypeScript file adds types only. - Java.
new StringBuilder(s).reverse(). The method treats a surrogate pair as one character, so the pair keeps its order. For graphemes, the regular expression\Xmatches one extended grapheme cluster. The code collects the matches and reverses the list. - C#.
s.EnumerateRunes()yields oneRunefor each Unicode scalar value. The code appends the runes in the opposite order. For graphemes,StringInfo.GetTextElementEnumeratoryields text elements. The API reference calls a text element an extended grapheme cluster. - Go.
utf8.ValidStringchecks the bytes first. Then[]rune(s)gives the code points,slices.Reversereverses them, andstring(runes)encodes them again. The check is necessary, because the conversion to[]runedoes not report bad bytes. - Rust.
s.chars().rev().collect(). Acharis a Unicode scalar value. A&stris always valid UTF-8, so the function has no error case. - C. The function reads the length of each UTF-8 sequence from its first byte and checks the sequence against the syntax of RFC 3629. Then it copies the bytes to the mirror position in the output buffer. It makes one pass and allocates nothing.
- C++. The same loop over a
std::string_view. The function returnsstd::expected<std::string, ReverseError>. - Bash. In a UTF-8 locale,
${#s}and${s:i:1}count characters, so a loop from the end reverses the code points. The function setsLC_ALL=C.UTF-8in a local variable, becauseLC_CTYPEcontrols how Bash reads characters. First it sends the string throughiconv -f UTF-8 -t UTF-8, which fails on bad bytes.
Edge cases
The cases of reverse_code_points are in cases/basic.jsonl and cases/edge.jsonl. The cases of reverse_graphemes are in cases/graphemes.jsonl. The byte strings that must give an error are in cases/errors.jsonl.
emptyandsingle: the result is the input.two-byteandthree-byte:Γ―is 2 bytes andζ₯is 3 bytes in UTF-8. A byte reversal puts the continuation bytes first, and the result is not valid UTF-8.astralandtwo-astral: π is 4 bytes in UTF-8 and a surrogate pair in UTF-16. A reversal by UTF-16 unit puts the low surrogate before the high surrogate.combining-mark:e, U+0301 COMBINING ACUTE ACCENT,x. The code point reversal givesx, U+0301,e, so the accent moves to thex. The case records this result on purpose.reverse_graphemesgivesx,e, U+0301, because rule GB9 does not break before an extending character.flag: the flag of France is the regional indicators F and R. The code point reversal gives R and F, so the flag is lost.- Grapheme cases:
flagskeeps each pair of regional indicators (GB12 and GB13).zwj-familykeeps an emoji ZWJ sequence (GB11).skin-tonekeeps U+1F3FD with its emoji, because an emoji modifier is in the class Extend (GB9).crlfkeeps CR LF together (GB3).hangul-jamokeeps a leading jamo with its vowel jamo (GB6). - Errors: the bytes
FF FE, a sequence cut by the end of the string, an encoded surrogate (ED A0 80) and an overlong form (C0 AF). RFC 3629 does not allow these bytes.
Pitfalls
- Byte reversal. Reverse the bytes of UTF-8 text and each multibyte sequence comes out backwards. Rust
String::from_utf8checks the bytes and returns an error. C code that reverses achararray gives the bad bytes to the caller with no error.
This code runs but gives a wrong answer on purpose.
fn main() {
let s = "naΓ―ve";
let bytes: Vec<u8> = s.bytes().rev().collect();
match String::from_utf8(bytes) {
Ok(t) => println!("bytes: {t}"),
Err(e) => println!("bytes: error: {e}"),
}
let t: String = s.chars().rev().collect();
println!("chars: {t}");
}
bytes: error: invalid utf-8 sequence of 1 bytes from index 2
chars: evΓ―an
- Reversal by UTF-16 unit. JavaScript
s.split("")splits the string into UTF-16 code units, so it breaks each surrogate pair. After the reversal, the low surrogate comes first, and the two units are no longer a pair. C#Array.Reverseons.ToCharArray()has the same bug, because acharis one UTF-16 code unit. The spread syntax splits by code point:
This code runs but gives a wrong answer on purpose.
const units = (t) => Array.from({ length: t.length }, (_, i) => t.charCodeAt(i).toString(16).padStart(4, "0")).join(" ");
const s = "aπb";
console.log("input: ", units(s));
console.log("split: ", units(s.split("").reverse().join("")));
console.log("spread: ", units([...s].reverse().join("")));
input: 0061 d83d de42 0062
split: 0062 de42 d83d 0061
spread: 0062 d83d de42 0061
- Code point reversal and grapheme clusters. Python
s[::-1], Rustchars().rev(), Go[]rune, JavaStringBuilder.reverseand the JavaScript spread syntax all reverse code points. A combining mark moves to the letter that was after it. A flag turns into a different pair of regional indicators. A ZWJ sequence comes out in the opposite order:
def codes(s: str) -> str:
return " ".join(f"U+{ord(c):04X}" for c in s)
for s in ["e\u0301x", "\U0001F1EB\U0001F1F7", "\U0001F468\u200d\U0001F466"]:
print(codes(s), "->", codes(s[::-1]))
U+0065 U+0301 U+0078 -> U+0078 U+0301 U+0065
U+1F1EB U+1F1F7 -> U+1F1F7 U+1F1EB
U+1F468 U+200D U+1F466 -> U+1F466 U+200D U+1F468
Reverse the grapheme clusters to keep each one whole:
const segmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
const reverse = (s) => Array.from(segmenter.segment(s), (part) => part.segment).reverse().join("");
const codes = (s) => [...s].map((c) => "U+" + c.codePointAt(0).toString(16).toUpperCase().padStart(4, "0")).join(" ");
for (const s of ["e\u0301x", "\u{1F1EB}\u{1F1F7}", "\u{1F468}\u200d\u{1F466}"]) {
console.log(codes(s), "->", codes(reverse(s)));
}
U+0065 U+0301 U+0078 -> U+0078 U+0065 U+0301
U+1F1EB U+1F1F7 -> U+1F1EB U+1F1F7
U+1F468 U+200D U+1F466 -> U+1F468 U+200D U+1F466
- Silent replacement in Go. A Go string holds any bytes. The conversion to
[]runeputs U+FFFD in place of a bad byte and gives no error. Callutf8.ValidStringfirst:
package main
import (
"fmt"
"slices"
"unicode/utf8"
)
func main() {
s := "caf\xc3"
runes := []rune(s)
slices.Reverse(runes)
for _, r := range runes {
fmt.Printf("U+%04X ", r)
}
fmt.Println()
fmt.Println("valid:", utf8.ValidString(s))
}
U+FFFD U+0066 U+0061 U+0063
valid: false
Related tasks
- Split a string: another job on a string, where the separator search works on bytes or units.
- Sort a list of records: a string key can compare by code unit or by code point.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/reverse-a-string/.
def reverse_code_points(s: str) -> str:
"""Return the code points of s in the opposite order.
A Python str is a sequence of code points, so a slice with step -1
reverses code points. It does not keep a combining mark on its base
letter, and it does not keep the parts of an emoji sequence together.
"""
return s[::-1]
test_reverse_string.py 30 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/reverse-a-string/.
import pytest
from reverse_string import reverse_code_points
CASES = {
"ascii": ("hello", "olleh"),
"two-words": ("abc def", "fed cba"),
"palindrome": ("racecar", "racecar"),
"empty": ("", ""),
"single": ("a", "a"),
"two-byte": ("naΓ―ve", "evΓ―an"),
"three-byte": ("ζ₯ζ¬θͺ", "θͺζ¬ζ₯"),
"astral": ("aπb", "bπa"),
"two-astral": ("ππ", "ππ"),
"combining-mark": ("e\u0301x", "x\u0301e"),
"flag": ("π«π·", "π·π«"),
}
@pytest.mark.parametrize("s, want", CASES.values(), ids=CASES.keys())
def test_reverse_code_points(s: str, want: str) -> None:
assert reverse_code_points(s) == want
@pytest.mark.parametrize("s", [s for s, _ in CASES.values()], ids=CASES.keys())
def test_twice_gives_the_input(s: str) -> None:
assert reverse_code_points(reverse_code_points(s)) == s
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reverse-a-string/.
#include "reverse_string.hpp"
#include <cstddef>
namespace {
// Returns the length of the UTF-8 sequence at the start of s, or 0 if the
// bytes are not valid UTF-8 (RFC 3629). It rejects overlong forms,
// surrogates and values above U+10FFFF.
std::size_t utf8_len(std::string_view s) {
auto byte = [&](std::size_t i) { return static_cast<unsigned char>(s[i]); };
const unsigned char c = byte(0);
std::size_t len = 0;
unsigned char lo = 0x80, hi = 0xBF; // the range of the second byte
if (c < 0x80) {
return 1;
} else if (c >= 0xC2 && c <= 0xDF) {
len = 2;
} else if (c >= 0xE0 && c <= 0xEF) {
len = 3;
if (c == 0xE0) lo = 0xA0; // no overlong form
if (c == 0xED) hi = 0x9F; // no surrogate
} else if (c >= 0xF0 && c <= 0xF4) {
len = 4;
if (c == 0xF0) lo = 0x90; // no overlong form
if (c == 0xF4) hi = 0x8F; // no value above U+10FFFF
} else {
return 0;
}
if (s.size() < len || byte(1) < lo || byte(1) > hi) return 0;
for (std::size_t j = 2; j < len; ++j) {
if ((byte(j) & 0xC0) != 0x80) return 0;
}
return len;
}
} // namespace
std::expected<std::string, ReverseError> reverse_code_points(std::string_view s) {
std::string out(s.size(), '\0');
for (std::size_t i = 0; i < s.size();) {
const std::size_t len = utf8_len(s.substr(i));
if (len == 0) return std::unexpected(ReverseError::invalid_utf8);
// The sequence at s[i] goes to the mirror position, with its bytes
// in the same order.
s.copy(out.data() + (s.size() - i - len), len, i);
i += len;
}
return out;
}
reverse_string.hpp 15 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reverse-a-string/.
// since: C++23 (std::expected)
#pragma once
#include <expected>
#include <string>
#include <string_view>
enum class ReverseError { invalid_utf8 };
// Returns the code points of the UTF-8 bytes s in the opposite order. Each
// code point keeps its bytes in their order.
std::expected<std::string, ReverseError> reverse_code_points(std::string_view s);
test_reverse_string.cpp 51 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reverse-a-string/.
#include <cstdio>
#include <string>
#include <utility>
#include <vector>
#include "reverse_string.hpp"
int main() {
int failures = 0;
const std::vector<std::pair<std::string, std::pair<std::string, std::string>>> cases = {
{"ascii", {"hello", "olleh"}},
{"two-words", {"abc def", "fed cba"}},
{"palindrome", {"racecar", "racecar"}},
{"empty", {"", ""}},
{"single", {"a", "a"}},
{"two-byte", {"naΓ―ve", "evΓ―an"}},
{"three-byte", {"ζ₯ζ¬θͺ", "θͺζ¬ζ₯"}},
{"astral", {"aπb", "bπa"}},
{"two-astral", {"ππ", "ππ"}},
{"combining-mark", {"e\u0301x", "x\u0301e"}},
{"flag", {"π«π·", "π·π«"}},
};
for (const auto& [name, io] : cases) {
auto got = reverse_code_points(io.first);
if (!got.has_value() || *got != io.second) {
std::fprintf(stderr, "case %s failed\n", name.c_str());
++failures;
}
}
const std::vector<std::pair<std::string, std::string>> invalid = {
{"invalid-byte", "\xff\xfe"},
{"truncated", "caf\xc3"},
{"encoded-surrogate", "a\xed\xa0\x80" "b"},
{"overlong", "\xc0\xaf"},
};
for (const auto& [name, s] : invalid) {
auto got = reverse_code_points(s);
if (got.has_value() || got.error() != ReverseError::invalid_utf8) {
std::fprintf(stderr, "case %s: no invalid_utf8 error\n", name.c_str());
++failures;
}
}
if (failures != 0) return 1;
std::puts("all tests passed");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reverse-a-string/.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.MatchResult;
import java.util.regex.Pattern;
public final class ReverseString {
private ReverseString() {}
/**
* Returns the code points of s in the opposite order. StringBuilder.reverse treats a surrogate
* pair as one character, so the pair keeps its order.
*/
public static String reverseCodePoints(String s) {
return new StringBuilder(s).reverse().toString();
}
// \X matches one extended grapheme cluster.
private static final Pattern GRAPHEME = Pattern.compile("\\X");
/** Returns the extended grapheme clusters of s in the opposite order. */
public static String reverseGraphemes(String s) {
List<String> parts = new ArrayList<>(GRAPHEME.matcher(s).results().map(MatchResult::group).toList());
Collections.reverse(parts);
return String.join("", parts);
}
}
ReverseStringTest.java 50 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reverse-a-string/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class ReverseStringTest {
static Stream<Arguments> codePointCases() {
return Stream.of(
Arguments.of("ascii", "hello", "olleh"),
Arguments.of("two-words", "abc def", "fed cba"),
Arguments.of("palindrome", "racecar", "racecar"),
Arguments.of("empty", "", ""),
Arguments.of("single", "a", "a"),
Arguments.of("two-byte", "naΓ―ve", "evΓ―an"),
Arguments.of("three-byte", "ζ₯ζ¬θͺ", "θͺζ¬ζ₯"),
Arguments.of("astral", "aπb", "bπa"),
Arguments.of("two-astral", "ππ", "ππ"),
Arguments.of("combining-mark", "e\u0301x", "x\u0301e"),
Arguments.of("flag", "π«π·", "π·π«"));
}
static Stream<Arguments> graphemeCases() {
return Stream.of(
Arguments.of("ascii", "abc", "cba"),
Arguments.of("empty", "", ""),
Arguments.of("combining-mark", "e\u0301x", "xe\u0301"),
Arguments.of("flags", "π«π·π©πͺ", "π©πͺπ«π·"),
Arguments.of("zwj-family", "aπ¨\u200dπ©\u200dπ§b", "bπ¨\u200dπ©\u200dπ§a"),
Arguments.of("skin-tone", "ππ½!", "!ππ½"),
Arguments.of("crlf", "a\r\nb", "b\r\na"),
Arguments.of("hangul-jamo", "\u1100\u1161x", "x\u1100\u1161"));
}
@ParameterizedTest(name = "{0}")
@MethodSource("codePointCases")
void reversesCodePoints(String name, String s, String want) {
assertEquals(want, ReverseString.reverseCodePoints(s), name);
}
@ParameterizedTest(name = "{0}")
@MethodSource("graphemeCases")
void reversesGraphemes(String name, String s, String want) {
assertEquals(want, ReverseString.reverseGraphemes(s), name);
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reverse-a-string/.
#include "reverse_string.h"
#include <errno.h>
#include <string.h>
// utf8_len returns the length of the UTF-8 sequence at the start of s[0..n),
// or 0 if the bytes are not valid UTF-8 (RFC 3629). It rejects overlong
// forms, surrogates and values above U+10FFFF.
static size_t utf8_len(const unsigned char *s, size_t n) {
unsigned char c = s[0];
size_t len;
unsigned char lo = 0x80, hi = 0xBF; // the range of the second byte
if (c < 0x80) {
return 1;
} else if (c >= 0xC2 && c <= 0xDF) {
len = 2;
} else if (c >= 0xE0 && c <= 0xEF) {
len = 3;
if (c == 0xE0) lo = 0xA0; // no overlong form
if (c == 0xED) hi = 0x9F; // no surrogate
} else if (c >= 0xF0 && c <= 0xF4) {
len = 4;
if (c == 0xF0) lo = 0x90; // no overlong form
if (c == 0xF4) hi = 0x8F; // no value above U+10FFFF
} else {
return 0;
}
if (n < len || s[1] < lo || s[1] > hi) return 0;
for (size_t j = 2; j < len; j++) {
if ((s[j] & 0xC0) != 0x80) return 0;
}
return len;
}
int reverse_code_points(const char *s, size_t n, char *out) {
const unsigned char *u = (const unsigned char *)s;
for (size_t i = 0; i < n;) {
size_t len = utf8_len(u + i, n - i);
if (len == 0) {
errno = EILSEQ;
return -1;
}
// The sequence at s[i] goes to the mirror position, with its bytes
// in the same order.
memcpy(out + (n - i - len), s + i, len);
i += len;
}
return 0;
}
reverse_string.h 15 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reverse-a-string/.
#ifndef REVERSE_STRING_H
#define REVERSE_STRING_H
#include <stddef.h>
// reverse_code_points writes the code points of the UTF-8 bytes s[0..n) in
// the opposite order to out, which has room for n bytes, and returns 0.
// Each code point keeps its bytes in their order. If s is not valid UTF-8,
// it returns -1 and sets errno to EILSEQ, and out holds no result.
int reverse_code_points(const char *s, size_t n, char *out);
#endif
test_reverse_string.c 52 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reverse-a-string/.
#include "reverse_string.h"
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int failures = 0;
static void check(const char *name, const char *s, const char *want) {
size_t n = strlen(s);
char out[64];
if (reverse_code_points(s, n, out) != 0 || memcmp(out, want, n) != 0 || strlen(want) != n) {
fprintf(stderr, "case %s failed\n", name);
failures++;
}
}
static void check_invalid(const char *name, const char *s) {
char out[64];
errno = 0;
if (reverse_code_points(s, strlen(s), out) != -1 || errno != EILSEQ) {
fprintf(stderr, "case %s: no EILSEQ error\n", name);
failures++;
}
}
int main(void) {
check("ascii", "hello", "olleh");
check("two-words", "abc def", "fed cba");
check("palindrome", "racecar", "racecar");
check("empty", "", "");
check("single", "a", "a");
check("two-byte", "naΓ―ve", "evΓ―an");
check("three-byte", "ζ₯ζ¬θͺ", "θͺζ¬ζ₯");
check("astral", "aπb", "bπa");
check("two-astral", "ππ", "ππ");
check("combining-mark", "e\u0301x", "x\u0301e");
check("flag", "π«π·", "π·π«");
check_invalid("invalid-byte", "\xff\xfe");
check_invalid("truncated", "caf\xc3");
check_invalid("encoded-surrogate", "a\xed\xa0\x80" "b");
check_invalid("overlong", "\xc0\xaf");
if (failures != 0) return 1;
puts("all tests passed");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reverse-a-string/.
using System.Globalization;
using System.Text;
public static class ReverseString
{
// Returns the code points of s in the opposite order. EnumerateRunes
// yields Unicode scalar values, so a surrogate pair stays together.
// Array.Reverse on s.ToCharArray() would break the pair.
public static string ReverseCodePoints(string s)
{
var builder = new StringBuilder(s.Length);
foreach (Rune rune in s.EnumerateRunes().Reverse())
{
builder.Append(rune);
}
return builder.ToString();
}
// Returns the text elements of s in the opposite order. The API reference
// calls a text element an extended grapheme cluster. Before .NET 5,
// StringInfo handled some grapheme clusters incorrectly.
public static string ReverseGraphemes(string s)
{
var parts = new List<string>();
TextElementEnumerator elements = StringInfo.GetTextElementEnumerator(s);
while (elements.MoveNext())
{
parts.Add(elements.GetTextElement());
}
parts.Reverse();
return string.Concat(parts);
}
}
ReverseStringTests.cs 50 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reverse-a-string/.
using Xunit;
public sealed class ReverseStringTests
{
public static TheoryData<string, string, string> CodePointCases => new()
{
{ "ascii", "hello", "olleh" },
{ "two-words", "abc def", "fed cba" },
{ "palindrome", "racecar", "racecar" },
{ "empty", "", "" },
{ "single", "a", "a" },
{ "two-byte", "naΓ―ve", "evΓ―an" },
{ "three-byte", "ζ₯ζ¬θͺ", "θͺζ¬ζ₯" },
{ "astral", "aπb", "bπa" },
{ "two-astral", "ππ", "ππ" },
{ "combining-mark", "e\u0301x", "x\u0301e" },
{ "flag", "π«π·", "π·π«" },
};
public static TheoryData<string, string, string> GraphemeCases => new()
{
{ "ascii", "abc", "cba" },
{ "empty", "", "" },
{ "combining-mark", "e\u0301x", "xe\u0301" },
{ "flags", "π«π·π©πͺ", "π©πͺπ«π·" },
{ "zwj-family", "aπ¨\u200dπ©\u200dπ§b", "bπ¨\u200dπ©\u200dπ§a" },
{ "skin-tone", "ππ½!", "!ππ½" },
{ "crlf", "a\r\nb", "b\r\na" },
{ "hangul-jamo", "\u1100\u1161x", "x\u1100\u1161" },
};
[Theory]
[MemberData(nameof(CodePointCases))]
public void ReversesCodePoints(string name, string s, string want)
{
Assert.False(string.IsNullOrEmpty(name));
Assert.Equal(want, ReverseString.ReverseCodePoints(s));
}
[Theory]
[MemberData(nameof(GraphemeCases))]
public void ReversesGraphemes(string name, string s, string want)
{
Assert.False(string.IsNullOrEmpty(name));
Assert.Equal(want, ReverseString.ReverseGraphemes(s));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reverse-a-string/.
// Returns the code points of s in the opposite order. The spread syntax uses
// the string iterator, which yields code points, so a surrogate pair stays
// together. s.split("") would yield UTF-16 code units and break the pairs.
export function reverseCodePoints(s) {
return [...s].reverse().join("");
}
const graphemes = new Intl.Segmenter(undefined, { granularity: "grapheme" });
// Returns the extended grapheme clusters of s in the opposite order. A letter
// keeps its combining marks, and an emoji sequence stays in one piece.
export function reverseGraphemes(s) {
return Array.from(graphemes.segment(s), (part) => part.segment)
.reverse()
.join("");
}
reverseString.test.js 44 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reverse-a-string/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { reverseCodePoints, reverseGraphemes } from "./reverseString.js";
const codePointCases = [
["ascii", "hello", "olleh"],
["two-words", "abc def", "fed cba"],
["palindrome", "racecar", "racecar"],
["empty", "", ""],
["single", "a", "a"],
["two-byte", "naΓ―ve", "evΓ―an"],
["three-byte", "ζ₯ζ¬θͺ", "θͺζ¬ζ₯"],
["astral", "aπb", "bπa"],
["two-astral", "ππ", "ππ"],
["combining-mark", "e\u0301x", "x\u0301e"],
["flag", "π«π·", "π·π«"],
];
const graphemeCases = [
["ascii", "abc", "cba"],
["empty", "", ""],
["combining-mark", "e\u0301x", "xe\u0301"],
["flags", "π«π·π©πͺ", "π©πͺπ«π·"],
["zwj-family", "aπ¨\u200dπ©\u200dπ§b", "bπ¨\u200dπ©\u200dπ§a"],
["skin-tone", "ππ½!", "!ππ½"],
["crlf", "a\r\nb", "b\r\na"],
["hangul-jamo", "\u1100\u1161x", "x\u1100\u1161"],
];
for (const [name, s, want] of codePointCases) {
test(`reverseCodePoints ${name}`, () => {
assert.equal(reverseCodePoints(s), want);
});
}
for (const [name, s, want] of graphemeCases) {
test(`reverseGraphemes ${name}`, () => {
assert.equal(reverseGraphemes(s), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reverse-a-string/.
// Returns the code points of s in the opposite order. The spread syntax uses
// the string iterator, which yields code points, so a surrogate pair stays
// together. s.split("") would yield UTF-16 code units and break the pairs.
export function reverseCodePoints(s: string): string {
return [...s].reverse().join("");
}
const graphemes = new Intl.Segmenter(undefined, { granularity: "grapheme" });
// Returns the extended grapheme clusters of s in the opposite order. A letter
// keeps its combining marks, and an emoji sequence stays in one piece.
export function reverseGraphemes(s: string): string {
return Array.from(graphemes.segment(s), (part) => part.segment)
.reverse()
.join("");
}
reverseString.test.ts 44 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reverse-a-string/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { reverseCodePoints, reverseGraphemes } from "./reverseString.ts";
const codePointCases: [string, string, string][] = [
["ascii", "hello", "olleh"],
["two-words", "abc def", "fed cba"],
["palindrome", "racecar", "racecar"],
["empty", "", ""],
["single", "a", "a"],
["two-byte", "naΓ―ve", "evΓ―an"],
["three-byte", "ζ₯ζ¬θͺ", "θͺζ¬ζ₯"],
["astral", "aπb", "bπa"],
["two-astral", "ππ", "ππ"],
["combining-mark", "e\u0301x", "x\u0301e"],
["flag", "π«π·", "π·π«"],
];
const graphemeCases: [string, string, string][] = [
["ascii", "abc", "cba"],
["empty", "", ""],
["combining-mark", "e\u0301x", "xe\u0301"],
["flags", "π«π·π©πͺ", "π©πͺπ«π·"],
["zwj-family", "aπ¨\u200dπ©\u200dπ§b", "bπ¨\u200dπ©\u200dπ§a"],
["skin-tone", "ππ½!", "!ππ½"],
["crlf", "a\r\nb", "b\r\na"],
["hangul-jamo", "\u1100\u1161x", "x\u1100\u1161"],
];
for (const [name, s, want] of codePointCases) {
test(`reverseCodePoints ${name}`, () => {
assert.equal(reverseCodePoints(s), want);
});
}
for (const [name, s, want] of graphemeCases) {
test(`reverseGraphemes ${name}`, () => {
assert.equal(reverseGraphemes(s), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reverse-a-string/.
// Package reversestring reverses the code points of a UTF-8 string.
package reversestring
import (
"errors"
"slices"
"unicode/utf8"
)
// ErrInvalidUTF8 reports bytes that are not valid UTF-8.
var ErrInvalidUTF8 = errors.New("reversestring: invalid UTF-8")
// ReverseCodePoints returns the code points of s in the opposite order.
// A Go string holds any bytes. The conversion to []rune puts U+FFFD in place
// of a bad byte, so the function checks the bytes first.
func ReverseCodePoints(s string) (string, error) {
if !utf8.ValidString(s) {
return "", ErrInvalidUTF8
}
runes := []rune(s)
slices.Reverse(runes)
return string(runes), nil
}
reverse_string_test.go 48 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reverse-a-string/.
package reversestring
import (
"errors"
"testing"
)
func TestCases(t *testing.T) {
cases := []struct{ name, s, want string }{
{"ascii", "hello", "olleh"},
{"two-words", "abc def", "fed cba"},
{"palindrome", "racecar", "racecar"},
{"empty", "", ""},
{"single", "a", "a"},
{"two-byte", "naΓ―ve", "evΓ―an"},
{"three-byte", "ζ₯ζ¬θͺ", "θͺζ¬ζ₯"},
{"astral", "aπb", "bπa"},
{"two-astral", "ππ", "ππ"},
{"combining-mark", "e\u0301x", "x\u0301e"},
{"flag", "π«π·", "π·π«"},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
got, err := ReverseCodePoints(c.s)
if err != nil || got != c.want {
t.Errorf("ReverseCodePoints(%q) = %q, %v; want %q, nil", c.s, got, err, c.want)
}
})
}
}
func TestInvalidUTF8(t *testing.T) {
for name, s := range map[string]string{
"invalid-byte": "\xff\xfe",
"truncated": "caf\xc3",
"encoded-surrogate": "a\xed\xa0\x80b",
"overlong": "\xc0\xaf",
} {
t.Run(name, func(t *testing.T) {
if got, err := ReverseCodePoints(s); !errors.Is(err, ErrInvalidUTF8) || got != "" {
t.Errorf("ReverseCodePoints(%q) = %q, %v; want \"\", ErrInvalidUTF8", s, got, err)
}
})
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reverse-a-string/.
/// Returns the code points of `s` in the opposite order.
///
/// A `char` is a Unicode scalar value, so `chars().rev()` reverses code
/// points. A combining mark moves to the letter that was after it, because
/// the standard library has no grapheme iteration.
pub fn reverse_code_points(s: &str) -> String {
s.chars().rev().collect()
}
tests/reverse_string_test.rs 26 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reverse-a-string/.
use algo_reverse_a_string::reverse_code_points;
#[test]
fn cases() {
let cases = [
("ascii", "hello", "olleh"),
("two-words", "abc def", "fed cba"),
("palindrome", "racecar", "racecar"),
("empty", "", ""),
("single", "a", "a"),
("two-byte", "naΓ―ve", "evΓ―an"),
("three-byte", "ζ₯ζ¬θͺ", "θͺζ¬ζ₯"),
("astral", "aπb", "bπa"),
("two-astral", "ππ", "ππ"),
("combining-mark", "e\u{301}x", "x\u{301}e"),
("flag", "π«π·", "π·π«"),
];
for (name, s, want) in cases {
let got = reverse_code_points(s);
assert_eq!(got, want, "case {name}");
assert_eq!(got.len(), s.len(), "case {name}: the byte length changed");
}
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/reverse-a-string/.
# reverse_code_points STRING
# Prints the characters of STRING in the opposite order. In a UTF-8 locale a character is one code point.
# Returns a nonzero status, and prints nothing on stdout, if STRING is not valid UTF-8.
reverse_code_points() {
local LC_ALL=C.UTF-8 # ${#s} and ${s:i:1} count characters only in a UTF-8 locale.
local s=$1 out='' i
# iconv stops with an error on a bad byte sequence.
printf '%s' "$s" | iconv -f UTF-8 -t UTF-8 >/dev/null || return
for ((i = ${#s} - 1; i >= 0; i--)); do
out+=${s:i:1}
done
printf '%s\n' "$out"
}
test_reverse_string.bats 39 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/reverse-a-string/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/reverse_string.sh"
}
check() { # check STRING WANT
run reverse_code_points "$1"
[ "$status" -eq 0 ]
[ "$output" = "$2" ]
}
@test "ascii" { check 'hello' 'olleh'; }
@test "two-words" { check 'abc def' 'fed cba'; }
@test "palindrome" { check 'racecar' 'racecar'; }
@test "empty" { check '' ''; }
@test "single" { check 'a' 'a'; }
@test "two-byte" { check 'naΓ―ve' 'evΓ―an'; }
@test "three-byte" { check 'ζ₯ζ¬θͺ' 'θͺζ¬ζ₯'; }
@test "astral" { check 'aπb' 'bπa'; }
@test "two-astral" { check 'ππ' 'ππ'; }
# U+0301 COMBINING ACUTE ACCENT is CC 81 in UTF-8.
@test "combining-mark" { check $'e\xcc\x81x' $'x\xcc\x81e'; }
@test "flag" { check 'π«π·' 'π·π«'; }
invalid() { # invalid BYTES
run --separate-stderr reverse_code_points "$(printf '%b' "$1")"
[ "$status" -ne 0 ]
[ -z "$output" ]
}
@test "invalid-byte" { invalid '\xff\xfe'; }
@test "truncated" { invalid 'caf\xc3'; }
@test "encoded-surrogate" { invalid 'a\xed\xa0\x80b'; }
@test "overlong" { invalid '\xc0\xaf'; }
References
- Unicode Standard Annex 29, Unicode Text Segmentation, revision 49, Section 3, Grapheme Cluster Boundaries; Section 3.1.1, rules GB3, GB6, GB9, GB11, GB12 and GB13; Table 2, the Extend and Regional_Indicator rows
- F. Yergeau, RFC 3629, UTF-8, a transformation format of ISO 10646 (2003), Section 3, Section 4 and Section 10
- Microsoft Learn, Introduction to character encoding in .NET, The string and char types; Surrogate pairs; The Rune type as a scalar value; Grapheme clusters
- .NET API reference, StringInfo, Remarks; the GetNextTextElementLength and GetTextElementEnumerator methods
- The Python Standard Library, Built-in Types, Text Sequence Type, str; Common Sequence Operations, note 5
- MDN Web Docs, String.prototype.split(), Description, the warning about the empty separator
- MDN Web Docs, String.prototype[Symbol.iterator](), Description
- MDN Web Docs, Intl.Segmenter() constructor, Parameters, the granularity option
- Java SE 25 API, java.lang.String, the class description
- Java SE 25 API, java.lang.StringBuilder, reverse()
- Java SE 25 API, java.util.regex.Pattern, Unicode support; the summary row for \X
- The Go Programming Language Specification, String types; Conversions to and from a string type, rules 2 and 4; For statements with range clause
- Go standard library, package unicode/utf8, ValidString
- The Rust Standard Library, primitive type str, chars; Invariant
- The Rust Standard Library, std::string::String, from_utf8, Errors
- GNU Bash Reference Manual, Shell Parameter Expansion, ${#parameter} and ${parameter:offset:length}; Bash Variables, LC_ALL and LC_CTYPE
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
The native tests pass in 9 of 10 languages in this build.
Tag PMSCAQ Edit this page History Report an error Markdown