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 calledstring1and assigns it the value"Hello".let string2 = "World";: This creates a string variable calledstring2and assigns it the value"World".let comparison = string1.cmp(&string2);: This calls thecmp()method onstring1and passesstring2as an argument. This returns anOrderingenum which is assigned to thecomparisonvariable.println!("{:?}", comparison);: This prints the value of thecomparisonvariable to the console.
Helpful links
More of Rust
- How to ignore case in Rust regex?
- How to create a Rust regex from a string?
- How to perform matrix operations in Rust?
- How to replace strings using Rust regex?
- How do I get the last character from a string in Rust?
- How to use non-capturing groups in Rust regex?
- How to use regex lookahead in Rust?
- How to insert an element into a Rust HashMap if it does not already exist?
- How to get a capture group using Rust regex?
- How to use groups in a Rust regex?
See more codes...