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 variableswith the valueHello World!.let index = s.find("World");: This calls thefind()method on thesstring variable, passing in the substringWorldas an argument.Some(6): This is the output of thefind()method, which isSome(index)if the substring is found, orNoneif it is not found. In this case, the substringWorldis found at index 6.
Helpful links
More of Rust
- How to compare two Rust HashMaps?
- How to replace strings using Rust regex?
- How to use regex to match a double quote in Rust?
- Bitwise operator example in Rust
- How to insert an element into a Rust HashMap if it does not already exist?
- How to use Unicode in a regex in Rust?
- How to map a Rust slice?
- How to use non-capturing groups in Rust regex?
- How to convert struct to bytes in Rust
- How to loop until error in Rust
See more codes...