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
- Comparison is case-sensitive:
"Yes"and"yes"are different. To ignore case, lowercase both sides. (For plain ASCII text there's alsoa.eq_ignore_ascii_case(b), which doesn't build new strings.) <and>compare in dictionary-like order, character by character, using each character's Unicode number. All uppercase letters come before all lowercase ones, which is why"Zebra" < "apple". For a human-friendly order, compare lowercased copies.
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
- Comparing raw input. Text typed by a user usually ends with a newline:
"yes\n" == "yes"isfalse. Trim first. - Comparing a string with a
char:
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:
- exactly
hiorhello(the whole message) →Hello! How can I help? - a message containing
refundanywhere →Refunds take 5 days. - an empty message →
Say something! - anything else →
Sorry, I don't understand:followed by the message, trimmed but with its original case.
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:
- fewer than 8 characters →
too short - the password, lowercased, is
passwordorqwertyuiop→too common - no digit (
'0'to'9') anywhere →needs a digit - otherwise →
ok