rustHow do I compare a string and a str in Rust?
Comparing strings in Rust is done using the ==
operator. This operator will compare two strings and return true
if they are equal, and false
if they are not.
Example
let str1 = "Hello";
let str2 = "World";
println!("{}", str1 == str2);
Output example
false
The ==
operator compares two strings by comparing each character in the strings. If all characters in the strings are the same, then the strings are equal and the ==
operator will return true
.
In addition to the ==
operator, Rust also provides the str::eq
method which can be used to compare two strings. This method takes two &str
references as arguments and returns true
if the strings are equal, and false
if they are not.
Example
let str1 = "Hello";
let str2 = "World";
println!("{}", str1.eq(&str2));
Output example
false
Helpful links
More of Rust
- How to get a capture group using Rust regex?
- How to use regex with bytes in Rust?
- How to match the end of a line in a Rust regex?
- Hashshet example in Rust
- How to create a new Rust HashMap with values?
- How do I use a variable from another file in Rust?
- How to get the length of a Rust HashMap?
- How to get an element from a HashSet in Rust?
- How to implement PartialEq for a Rust HashMap?
- How to convert the keys of a Rust HashMap to a vector?
See more codes...