rustHow do you find a substring in a Rust string?
You can find a substring in a Rust string using the contains()
method. This method takes a &str
as an argument and returns a bool
indicating whether the string contains the substring.
Example code
let my_string = "Hello World!";
let substring = "World";
let result = my_string.contains(substring);
Output example
true
Code explanation
let my_string = "Hello World!";
: This line declares a variablemy_string
and assigns it the value of the string"Hello World!"
.let substring = "World";
: This line declares a variablesubstring
and assigns it the value of the string"World"
.let result = my_string.contains(substring);
: This line calls thecontains()
method on themy_string
variable, passing in thesubstring
variable as an argument. The result of the method is assigned to theresult
variable.
Helpful links
More of Rust
- How to match whitespace with a regex in Rust?
- How to replace a capture group using Rust regex?
- How to use regex captures in Rust?
- How to convert the keys of a Rust HashMap to a vector?
- How to split a string with Rust regex?
- How to get a capture group using Rust regex?
- How to clear a Rust HashMap?
- How to perform matrix operations in Rust?
- Bitwise negation (NOT) usage in Rust
- How to use regex to match a double quote in Rust?
See more codes...