Exercism Reverse a String
pub fn reverse(input: &str) -> String {
input.chars().rev().collect()
}
The first solution was really easy, first I tried just a .reverse but that
doesn't exist on a string slice. Flipping through which functions I could call with the lsp
I saw chars() and that gives me an iterator over the chars in the string slice
which is perfect because I know I can reverse a iterator with rev() from there
I just have to collect() the iterator into the datatype that the function wants
to return and all tests passed.
Bonus
The bonus section of this exercise is trying to reverse a string where the characters are
uüu. I ran the tests first with
cargo test --features grapheme -- --include-ignored just to see what happens
and sure enough they failed with the following output.
---- grapheme_cluster_with_pre_combined_form stdout ----
thread 'grapheme_cluster_with_pre_combined_form' (35210) panicked at tests/reverse_string.rs:72:5:
assertion `left == right` failed
left: "dnatsnehctsr\u{308}uW"
right: "dnatsnehctsru\u{308}W"
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
---- grapheme_clusters stdout ----
thread 'grapheme_clusters' (35211) panicked at tests/reverse_string.rs:82:5:
assertion `left == right` failed
left: "มรกแรปโนย\u{e35}ขเ\u{e49}\u{e39}ผ"
right: "มรกแรปโนยข\u{e35}เผ\u{e39}\u{e49}"
the interesting bits here are the \u{308} which isn't an ascii character which is where I am
guessing the issue is coming from. Turns out \u{308} is the utf code for the
unicode character ◌̈ . The hint given to use for the bonus is grapheme clusters.
The section
Bytes, Scalar Values, and Grapheme Clusters
in the rust book is relevant. So in the string above we need u + \u{308} to be
treated as one letter, which we can do if we process the string slice with grapheme
clusters. The crate
unicode-segmentation gives
us the function graphemes(true), true is passed because it then uses exteneded
grapheme clusters over legacy which is recommended for general processing. Replacing
chars() with graphemes(true) and then all tests pass. This was
fun.