rustHow do I compare strings in Rust?
Strings in Rust can be compared using the cmp() method. This method returns an Ordering enum which can be used to determine if two strings are equal, one is greater than the other, or one is less than the other.
Example
let string1 = "Hello";
let string2 = "World";
let comparison = string1.cmp(&string2);
println!("{:?}", comparison);Output example
LessCode explanation
- let string1 = "Hello";: This creates a string variable called- string1and assigns it the value- "Hello".
- let string2 = "World";: This creates a string variable called- string2and assigns it the value- "World".
- let comparison = string1.cmp(&string2);: This calls the- cmp()method on- string1and passes- string2as an argument. This returns an- Orderingenum which is assigned to the- comparisonvariable.
- println!("{:?}", comparison);: This prints the value of the- comparisonvariable to the console.
Helpful links
More of Rust
- Regex example to match multiline string in Rust?
- How to use regex to match a double quote in Rust?
- How to convert the keys of a Rust HashMap to a vector?
- How to extend struct from another struct in Rust
- How to replace a capture group using Rust regex?
- How to replace strings using Rust regex?
- How to match the end of a line in a Rust regex?
- How to perform matrix operations in Rust?
- How to declare a constant HashSet in Rust?
- How to yield a thread in Rust?
See more codes...