0

How do I reverse a string in Rust 0.9?

According to rosettacode.org this worked in 0.8:

let reversed:~str = "一二三四五六七八九十".rev_iter().collect(); 

... but I can't get iterators working on strings in 0.9.

Also tried std::str::StrSlice::bytes_rev but I haven't figured out a clean way to convert the result back into a string without the compiler choking.

Greg Malcolm
  • 3,238
  • 4
  • 23
  • 24

1 Answers1

2

First of all iteration over bytes and reversing will break multibyte characters (you want iteration over chars)

let s = ~"abc";
let s2: ~str = s.chars_rev().collect();
println!("{:?}", s2);
Arjan
  • 19,957
  • 2
  • 55
  • 48
  • 2
    Note that this won't work as expected if you have any decomposed characters, such as "e\u0301" (é), as it will swap those two characters and the COMBINING ACUTE ACCENT will then affect the wrong character. – Lily Ballard Feb 23 '14 at 22:37
  • 1
    As @KevinBallard says, this iterates over individual `char`s (which are Unicode codepoints) and so the reversal just reorders codepoints. True grapheme reordering (for more correct Unicode reversal) requires grapheme handling, which the Rust stdlib currently lacks entirely. :( – huon Feb 24 '14 at 11:25