rustHow do I find the index of a substring in a string in Rust?
The find()
method of the str
type can be used to find the index of a substring in a string in Rust.
Example code
let s = "Hello World!";
let index = s.find("World");
Output example
Some(6)
The find()
method takes a &str
as an argument and returns an Option<usize>
which is Some(index)
if the substring is found, or None
if it is not found.
Code explanation
let s = "Hello World!";
: This declares a string variables
with the valueHello World!
.let index = s.find("World");
: This calls thefind()
method on thes
string variable, passing in the substringWorld
as an argument.Some(6)
: This is the output of thefind()
method, which isSome(index)
if the substring is found, orNone
if it is not found. In this case, the substringWorld
is found at index 6.
Helpful links
More of Rust
- How to get a capture group using Rust regex?
- How to split a string by regex in Rust?
- How to use regex to match a double quote in Rust?
- How to use regex with bytes in Rust?
- How to implement PartialEq for a Rust HashMap?
- How to use regex lookahead in Rust?
- How to use captures_iter with regex in Rust?
- How to use regex to match a group in Rust?
- How to perform matrix operations in Rust?
- How to declare a matrix in Rust?
See more codes...