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
Less
Code explanation
let string1 = "Hello";
: This creates a string variable calledstring1
and assigns it the value"Hello"
.let string2 = "World";
: This creates a string variable calledstring2
and assigns it the value"World"
.let comparison = string1.cmp(&string2);
: This calls thecmp()
method onstring1
and passesstring2
as an argument. This returns anOrdering
enum which is assigned to thecomparison
variable.println!("{:?}", comparison);
: This prints the value of thecomparison
variable to the console.
Helpful links
More of Rust
- How to replace a capture group using Rust regex?
- How to replace strings using Rust regex?
- How to calculate the inverse of a matrix in Rust?
- How to replace all matches using Rust regex?
- How to convert a Rust HashMap to JSON?
- How to get a capture group using Rust regex?
- How to match the end of a line in a Rust regex?
- How to convert the keys of a Rust HashMap to a vector?
- How to get an entry from a HashSet in Rust?
- How to create a new Rust HashMap with values?
See more codes...