RustArena

Step 6 of 6

Comparing strings

== and != compare the text of two strings, character by character. They work between a String and a &str in either order:

fn main() {
    let answer = String::from("yes");
    println!("{}", answer == "yes");
    println!("{}", "Yes" == "yes");
    println!("{}", answer.to_lowercase() == "YES".to_lowercase());
    println!("{}", "apple" < "banana");
    println!("{}", "Zebra" < "apple");
}
true
false
true
true
true

Choosing what to do based on text

An if / else if chain handles commands. Clean the input first, then compare:

fn reply(cmd: &str) -> String {
    let cmd = cmd.trim().to_lowercase();
    if cmd == "start" {
        "Starting engine".to_string()
    } else if cmd == "stop" {
        "Stopping engine".to_string()
    } else {
        format!("Unknown command: {cmd}")
    }
}

fn main() {
    println!("{}", reply("START "));
    println!("{}", reply("stop"));
    println!("{}", reply("jump"));
}
Starting engine
Stopping engine
Unknown command: jump

let cmd = cmd.trim().to_lowercase(); shadows the &str parameter with a cleaned-up String, a common idiom. Module 14 introduces match, which expresses this kind of choice even more neatly.

Common mistakes

fn main() {
    let answer = String::from("y");
    if answer == 'y' {
        println!("ok");
    }
}
error[E0277]: can't compare `String` with `char`

'y' is a char, "y" is a string. Compare with "y".

Your task

Write bot_reply(msg) for a support chat bot. Ignore spaces around the message and ignore case, then:

Challenge 2

Write same_user(a, b), which returns true when two usernames are the same once you ignore spaces around them and upper/lower case. For example same_user(" Ferris", "ferris ") is true.

Challenge 3

Write check_password(p), which returns the first problem it finds, checking in this order:

  1. fewer than 8 characters → too short
  2. the password, lowercased, is password or qwertyuiop → too common
  3. no digit ('0' to '9') anywhere → needs a digit
  4. otherwise → ok

Previous: Changing case, searching, replacing and trimming