Complete the code to print each character of the string.
let s = "hello"; for c in s.[1]() { println!("{}", c); }
The chars() method returns an iterator over the characters of the string, allowing you to access each character one by one.
Complete the code to get the first character of the string safely.
let s = "world"; let first_char = s.[1]().next(); match first_char { Some(c) => println!("First char: {}", c), None => println!("String is empty"), }
The chars() method returns an iterator over characters, and next() gets the first character if it exists.
Fix the error in accessing the character at index 2 of the string.
let s = "rustacean"; let c = s.[1](2..3).unwrap(); println!("Character at index 2: {}", c);
You cannot index a string directly by number because of UTF-8 encoding. Use get() with a range or chars().nth() to access characters safely.
Fill both blanks to create a new string with uppercase characters from the original string.
let s = "hello"; let upper_s: String = s.[1]().[2](|c| c.to_uppercase()).flatten().collect(); println!("{}", upper_s);
Use chars() to iterate characters, then map() to apply to_uppercase() on each character, and finally collect into a String.
Fill all three blanks to create a vector of characters from the string and print the third character.
let s = "example"; let chars_vec: Vec<char> = s.[1]().collect(); let third_char = chars_vec.[2](2); println!("Third character: {}", third_char.[3]());
Use chars() to get characters, collect into a vector, then use get(2) to safely access the third character, and unwrap() to get the value from the Option.
