Challenge - 5 Problems
String Traversal Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of iterating over a UTF-8 string's chars
What is the output of this Rust code that prints each character of the string on a new line?
DSA Rust
fn main() {
let s = "héllo";
for c in s.chars() {
println!("{}", c);
}
}Attempts:
2 left
💡 Hint
Remember that println! adds a newline after each character.
✗ Incorrect
The chars() iterator yields each Unicode scalar value. println! prints each on its own line, so output shows each character followed by a newline.
❓ Predict Output
intermediateIndexing a Rust string slice
What happens when you run this Rust code?
DSA Rust
fn main() {
let s = "hello";
let c = s[1];
println!("{}", c);
}Attempts:
2 left
💡 Hint
Rust strings cannot be indexed by integer directly because of UTF-8 encoding.
✗ Incorrect
Rust strings are UTF-8 encoded and do not support direct indexing by integer. This code causes a compile-time error.
🔧 Debug
advancedFix the code to print the third character of a string
This Rust code tries to print the third character of a string but fails. Which option fixes it correctly?
DSA Rust
fn main() {
let s = "rustacean";
let c = s[2];
println!("{}", c);
}Attempts:
2 left
💡 Hint
Use chars() iterator and nth() to get character by position.
✗ Incorrect
Option B uses chars().nth(2) to get the third character safely. Option B is invalid because slicing string by byte indices may panic if not on char boundary. Option B casts a byte to char incorrectly. Option B returns a &str slice but get() returns Option<&str>, so unwrap() is needed but slicing must be on char boundary.
🧠 Conceptual
advancedWhy can't Rust strings be indexed by integer?
Why does Rust not allow direct indexing of String or &str by integer like s[0]?
Attempts:
2 left
💡 Hint
Think about how UTF-8 encoding affects character length.
✗ Incorrect
Rust strings are UTF-8 encoded, so characters can be 1 to 4 bytes. Indexing by integer would be ambiguous and unsafe because it might split a character.
❓ Predict Output
expertOutput of slicing a UTF-8 string with multi-byte characters
What is the output of this Rust code?
DSA Rust
fn main() {
let s = "café";
let slice = &s[0..3];
println!("{}", slice);
}Attempts:
2 left
💡 Hint
UTF-8 characters can be multiple bytes; slicing must be on valid character boundaries.
✗ Incorrect
The character 'é' is two bytes in UTF-8. Slicing from 0 to 3 bytes cuts into the middle of 'é', causing a runtime panic due to invalid UTF-8 slice.
