Bird
Raised Fist0
DSA Rustprogramming~10 mins

String Traversal and Character Access in DSA Rust - Execution Trace

Choose your learning style10 modes available
Concept Flow - String Traversal and Character Access
Start with String
↓
Initialize index = 0
↓
Check: index < string length?
No→End Traversal
Yes↓
Access character at index
↓
Use or print character
↓
Increment index
↩Back to Check
This flow shows how to move through a string one character at a time by using an index from 0 up to the string's length.
Execution Sample
DSA Rust
let s = "hello";
for i in 0..s.len() {
    let c = s.chars().nth(i).unwrap();
    println!("{}", c);
}
This code prints each character of the string "hello" one by one.
Execution Table
StepIndex iCondition i < s.len()Character AccessedOutput
100 < 5 = true'h'h
211 < 5 = true'e'e
322 < 5 = true'l'l
433 < 5 = true'l'l
544 < 5 = true'o'o
655 < 5 = falseN/AEnd loop
💡 Index reaches 5 which is equal to string length, so condition fails and loop ends.
Variable Tracker
VariableStartAfter 1After 2After 3After 4After 5Final
i0123455
cN/A'h''e''l''l''o'N/A
Key Moments - 2 Insights
Why do we use s.chars().nth(i).unwrap() instead of s[i] to get a character?
Rust strings are UTF-8 encoded and do not support direct indexing like s[i]. Using s.chars().nth(i).unwrap() safely accesses the i-th character. This is shown in execution_table rows 1-5 where each character is accessed this way.
What happens when index i equals the string length?
When i equals s.len(), the condition i < s.len() becomes false (see execution_table row 6), so the loop stops and no character is accessed.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what character is accessed at step 3?
A'e'
B'l'
C'h'
D'o'
💡 Hint
Check the 'Character Accessed' column at step 3 in the execution_table.
At which step does the loop condition become false?
AStep 4
BStep 5
CStep 6
DStep 7
💡 Hint
Look at the 'Condition i < s.len()' column to find when it becomes false.
If the string was "hi", what would be the final value of i in variable_tracker?
A2
B1
C3
D0
💡 Hint
The final i equals the string length, so check the length of "hi".
Concept Snapshot
String Traversal and Character Access in Rust:
- Use a loop from 0 to s.len() to traverse.
- Access characters with s.chars().nth(i).unwrap() safely.
- Loop ends when index reaches string length.
- Direct indexing s[i] is not allowed due to UTF-8 encoding.
- Print or use each character inside the loop.
Full Transcript
This lesson shows how to go through a string in Rust one character at a time. We start with an index at zero and check if it is less than the string's length. If yes, we get the character at that index using s.chars().nth(i).unwrap() because Rust strings cannot be indexed directly. We print the character and then increase the index by one. When the index reaches the string length, the loop stops. This way, we safely access each character in the string step by step.

Practice

(1/5)
1. What does the following Rust code print?
let s = "hello";
for c in s.chars() {
print!("{}-", c);
}
easy
A. h-e-l-l-o-
B. hello
C. h e l l o
D. h,e,l,l,o,

Solution

  1. Step 1: Understand the chars() method

    The chars() method returns an iterator over each character in the string s.
  2. Step 2: Trace the for loop printing

    Each character is printed followed by a dash, so output is h-e-l-l-o-.
  3. Final Answer:

    h-e-l-l-o- -> Option A
  4. Quick Check:

    chars() + print with dash = h-e-l-l-o- [OK]
Hint: chars() iterates characters; print each with dash [OK]
Common Mistakes:
  • Thinking chars() returns words
  • Ignoring the dash printed after each char
  • Confusing chars() with bytes()
2. Which of the following is the correct way to access the third character of a Rust string s safely?
easy
A. let c = s.bytes().nth(2).unwrap();
B. let c = s[2];
C. let c = s.get(2).unwrap();
D. let c = s.chars().nth(2).unwrap();

Solution

  1. Step 1: Understand string indexing in Rust

    Rust strings cannot be indexed directly by integer due to UTF-8 encoding, so s[2] is invalid.
  2. Step 2: Use chars().nth() to get character safely

    The chars() iterator allows accessing the nth character safely with nth(2) and unwrap() to get the value.
  3. Final Answer:

    let c = s.chars().nth(2).unwrap(); -> Option D
  4. Quick Check:

    chars().nth(2).unwrap() = correct char access [OK]
Hint: Use chars().nth(index).unwrap() for safe char access [OK]
Common Mistakes:
  • Using direct indexing like s[2]
  • Using get(2) which returns Option<&str> slice, not char
  • Using bytes() which returns u8, not char
3. What is the output of this Rust code?
let s = "rust";
let mut result = String::new();
for c in s.chars() {
if c == 'u' {
result.push('U');
} else {
result.push(c);
}
}
println!("{}", result);
medium
A. rust
B. rUSt
C. rUst
D. Rust

Solution

  1. Step 1: Iterate over each character in "rust"

    The loop goes over 'r', 'u', 's', 't' one by one.
  2. Step 2: Replace 'u' with 'U' and keep others same

    When character is 'u', push 'U' to result; else push original char.
  3. Final Answer:

    rUst -> Option C
  4. Quick Check:

    Only 'u' replaced by 'U' = rUst [OK]
Hint: Check character equality and push accordingly [OK]
Common Mistakes:
  • Replacing wrong characters
  • Not pushing characters correctly
  • Confusing uppercase and lowercase
4. Identify the error in this Rust code snippet:
let s = "hello";
let c = s[1];
println!("{}", c);
medium
A. s is not declared mutable
B. Cannot index string with integer directly
C. Missing semicolon after println!
D. println! macro syntax error

Solution

  1. Step 1: Check string indexing rules in Rust

    Rust strings are UTF-8 encoded and do not support direct indexing by integer like arrays.
  2. Step 2: Identify the invalid line

    The line let c = s[1]; causes a compile-time error because of invalid indexing.
  3. Final Answer:

    Cannot index string with integer directly -> Option B
  4. Quick Check:

    Direct indexing on String = error [OK]
Hint: Rust strings can't be indexed by integer directly [OK]
Common Mistakes:
  • Assuming s[1] works like array indexing
  • Ignoring UTF-8 encoding complexity
  • Thinking semicolon or macro syntax is the error
5. Given a string s, how can you create a new string containing only the vowels from s in Rust?
Choose the correct code snippet.
hard
A. let vowels: String = s.chars().filter(|c| "aeiou".contains(*c)).collect();
B. let vowels: String = s.bytes().filter(|b| b == b'a' || b == b'e').collect();
C. let vowels: String = s.get(0..5).unwrap().to_string();
D. let vowels: String = s.chars().map(|c| if "aeiou".contains(c) { c } else { ' ' }).collect();

Solution

  1. Step 1: Use chars() to iterate characters

    We need to check each character, so chars() is appropriate.
  2. Step 2: Filter vowels and collect into String

    Filter characters that are vowels using filter and collect them into a new String.
  3. Final Answer:

    let vowels: String = s.chars().filter(|c| "aeiou".contains(*c)).collect(); -> Option A
  4. Quick Check:

    chars() + filter vowels + collect() = correct [OK]
Hint: Filter chars with contains("aeiou") and collect to String [OK]
Common Mistakes:
  • Using bytes() which returns u8, not char
  • Using get() which slices string, not filters vowels
  • Replacing non-vowels with spaces instead of filtering
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard