rustrust string comparison
String comparison in Rust is done using the cmp
method. This method takes two strings as arguments and returns an Ordering
enum, which can be either Less
, Equal
, or Greater
.
Example code
let string1 = "Hello";
let string2 = "World";
let comparison = string1.cmp(&string2);
println!("{:?}", comparison);
Output example
Less
The cmp
method compares two strings lexicographically, meaning it compares the characters in each string one by one until it finds a difference. In the example above, the first character of string1
is H
, which is less than the first character of string2
, which is W
. Therefore, the comparison returns Less
.
Code explanation
let string1 = "Hello";
: This line creates a string variable calledstring1
and assigns it the valueHello
.let string2 = "World";
: This line creates a string variable calledstring2
and assigns it the valueWorld
.let comparison = string1.cmp(&string2);
: This line calls thecmp
method onstring1
and passesstring2
as an argument. Thecmp
method returns anOrdering
enum, which is stored in thecomparison
variable.println!("{:?}", comparison);
: This line prints the value of thecomparison
variable to the console.
Helpful links
More of Rust
- How to match whitespace with a regex in Rust?
- How to match a URL with a regex in Rust?
- How to use non-capturing groups in Rust regex?
- How to use regex to match a group in Rust?
- How to replace a capture group using Rust regex?
- How to replace all matches using Rust regex?
- How to create a slice from a string in Rust?
- How to replace strings using Rust regex?
- Hashshet example in Rust
- How to create a HashSet from a Vec in Rust?
See more codes...