Several questions on the String


#1

Hello!

  1. How to get a particular character of String? String is not indexable.
  2. How to get reverse string? There is a method in the standard library?

#2

Here are the docs for String: https://doc.rust-lang.org/std/string/struct.String.html

docs on string indexing, and why it is not simple: https://doc.rust-lang.org/stable/book/strings.html#indexing (spoiler: because it is not simple in real life)

If you want to index, you can get the bytes and index those:

fn main() {
    let b = "bors".as_bytes();
    println!("{:?}", b[0] as char);
}

(playpen)

and here is reversal:

fn main() {
    let b = "bors";
    let rev: String = b.chars().rev().collect();
    println!("{:?}", rev);
}

(playpen)


#3

Thanks.


#4

One thing to take away from this: Strings are UTF-8, and ‘character’ isn’t a thing in UTF-8. You have bytes, codepoints, and grapheme clusters. https://crates.io/crates/unicode-segmentation/ will give you iterators over the last ones.