rustHow do I check if a string contains a certain substring in Rust?
You can use the contains()
method to check if a string contains a certain substring in Rust.
Example
let my_string = "Hello World";
if my_string.contains("World") {
println!("The string contains the substring!");
}
Output example
The string contains the substring!
The contains()
method takes a &str
as an argument and returns a bool
indicating whether the string contains the substring.
Code explanation
let my_string = "Hello World";
: This declares a variablemy_string
and assigns it the value"Hello World"
.if my_string.contains("World") {
: This checks if the stringmy_string
contains the substring"World"
.println!("The string contains the substring!");
: This prints the message"The string contains the substring!"
if the string contains the substring.
Helpful links
More of Rust
- How to use regex to match a double quote in Rust?
- How to replace a capture group using Rust regex?
- How to replace strings using Rust regex?
- How to use regex lookahead in Rust?
- How to calculate the inverse of a matrix in Rust?
- How to use an enum in a Rust HashMap?
- How to use enum as hashmap key in Rust
- How to match the end of a line in a Rust regex?
- How to yield a thread in Rust?
- How to get a capture group using Rust regex?
See more codes...