Reverse a string correctly for non-ASCII input such as Cyrillic text
Write reverse, which returns the characters of s in reverse order, and explain why reversing the bytes of the string instead is wrong.
Requirements:
reverse("привет")returns"тевирп";reverse("")returns"".- Reverse Unicode scalar values (
chars). Grapheme clusters such aseplus a combining accent are out of scope, but say what your version does to them. - O(n) time; no
unsafe.
fn reverse(s: &str) -> String {
// your code here
}Write the implementation.
Do not add extra use lines unless the task says so explicitly.
s.chars().rev().collect() decodes UTF-8 and reverses in O(n). Reversing bytes would turn each multibyte letter into invalid UTF-8, which a String may never hold. chars() still splits grapheme clusters such as e plus an accent.
- Reversing
as_bytes()and callingString::from_utf8(…).unwrap(), which panics on any multibyte letter - Indexing
s[i]in a loop, which does not compile for strings - Assuming
chars().rev()keeps accents and emoji intact, although it splits grapheme clusters
- How would you reverse by grapheme clusters, and why does std not offer it?
- What does
String::from_utf8check, and why does it return aResult?
chars() decodes UTF-8 into Unicode scalar values, rev() walks them from the end — the Chars iterator can do that without an intermediate vector — and collect() builds a new String, encoding the characters back into UTF-8 itself. All together it is one pass, O(n).
fn reverse(s: &str) -> String {
s.chars().rev().collect()
}
fn main() {
println!("{} [{}]", reverse("привет"), reverse("")); // тевирп []
// reversing bytes: each letter «п» = [208, 191] would become [191, 208]
let mut bytes = "привет".as_bytes().to_vec();
bytes.reverse();
println!("{}", String::from_utf8(bytes).is_err()); // true — no longer UTF-8
// «é» as two chars: e and the combining accent U+0301
let cafe = "cafe\u{301}";
println!("{}", reverse(cafe).starts_with('\u{301}')); // true — the accent came off
}Reversing the bytes is wrong: a Cyrillic letter in UTF-8 is a lead byte plus a continuation byte, and after the reversal the continuation byte comes first, which is an invalid sequence. String::from_utf8 checks for that and returns Err, so unwrap would panic, and a String cannot hold invalid UTF-8 without unsafe. Walking chars() is right for Cyrillic, but a char is not yet a visible letter: «é» written as e plus a combining accent loses its accent after the reversal — it moves to the front of the string. Reversing by grapheme clusters needs the external crate unicode-segmentation (graphemes(true).rev()): the standard library does not include the Unicode segmentation rules.