find the first index of a character in a string in rust

To find the index of the first occurrence of a character in a Rust string, you can use the find() method. This method returns an Option<usize>, which will either contain the index of the first occurrence of the character or None if the character is not found. Here is an example:

main.rs
let my_string = String::from("Hello, world!");
let my_char = ',';

match my_string.find(my_char) {
    Some(index) => println!("The index of {} is {}", my_char, index),
    None => println!("{} not found in string", my_char),
}
228 chars
8 lines

In this example, the find() method is called on the my_string variable with the my_char variable as an argument. The result is then matched on using a pattern match. If the Option contains a value, the index of the character is printed out. If the Option is None, a message indicating that the character was not found is printed.

gistlibby LogSnag