Search code examples
rustrust-0.9

How do I reverse a string in 0.9?


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.


Solution

  • 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);