Comparing str.chars.nth(1) to char


Is there any way I can compare a char in a string to a char?

if str.chars().nth(1) == ’ ’ {
// Returns an error (Mismatched Types)

Sorry if my english is bad, I am not great with words


Yes, you can use str.chars().nth(1) == Some(' ') since nth returns an Option.

Note that this is not direct indexing like an array, because UTF-8 characters have variable width, so this has to scan through every character up to the one you’ve asked for. If you need frequent access, it might be better to look for a different approach.


Will an else expression be executed if str.chars().nth(1) doesnt match with Some(’ ') ?


Sure, you can write an if-else expression.

if str.chars().nth(1) == Some(' ') {
} else {
    println!("didn't match...");


Note: The else branch will execute even if there is no second (nth(1)) character. If you want to treat that case differently, you can use a match:

match str.chars().nth(1) {
    Some(' ') => {
        // A space
    Some(_) => {
        // Not a space
    None => {
        // No character.

Alternatively, if you know there are at last two characters in the string, you can unwrap the character returned by nth(1):

// Note: `expect(...)` is an alternative to `unwrap()` that takes an error message.
if str.chars().nth(1).expect("string not long enough") == ' ' {
    // Do something...


Thanks, late reply but this could help me