How to index a String in Rust

后端 未结 4 1355
囚心锁ツ
囚心锁ツ 2020-12-13 03:38

I am attempting to index a string in Rust, but the compiler throws an error. My code (Project Euler problem 4, playground):

fn is_palindrome(num: u64) ->          


        
4条回答
  •  猫巷女王i
    2020-12-13 04:07

    You can convert a String or &str to a vec of a chars and then index that vec.

    For example:

    fn main() {
        let s = "Hello world!";
        let my_vec: Vec = s.chars().collect();
        println!("my_vec[0]: {}", my_vec[0]);
        println!("my_vec[1]: {}", my_vec[1]);
    }
    
    

    Here you have a live example

提交回复
热议问题