Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Compare strings

  • cmp

  • Less

  • Equal

  • Greater

  • Ordering

  • We can use the regular <, >, == operators to compare both strings and string slices.

  • The cmp method returns a value from the Ordering enum.

fn main() {
    let x = "abc";
    let y = "abd";
    let z = "abd";
    println!("{}", x < y);
    println!("{:?}", x.cmp(y));
    println!("{}", y == z);
    println!("{:?}", y.cmp(y));
    println!();

    let x = String::from("abc");
    let y = String::from("abd");
    let z = String::from("abd");
    println!("{}", x < y);
    println!("{:?}", x.cmp(&y));
    println!("{}", y == z);
    println!("{:?}", y.cmp(&y));
}
true
Less
true
Equal

true
Less
true
Equal