find the first character in a string in rust

To find the first character of a Rust string, one way is to use indexing. Rust strings are encoded using UTF-8, so we need to make sure that the indexing is done correctly as Rust strings are not just plain byte arrays.

Here is an example code snippet to find the first character in a Rust string:

main.rs
fn main() {
    let s = "hello";
    let first_char = s.chars().nth(0);

    match first_char {
        Some(c) => println!("The first character is {}", c),
        None => println!("The string is empty"),
    }
}
214 chars
10 lines

In this code, we create a string s with the value "hello". Next, we use the chars() method to create an iterator over the characters in the string. We then use the nth() method to get the first character of the iterator, which in this case is the first character of the string.

The nth() method returns an Option value, which means it could be Some(character) or None if there are no characters in the string. In this code, we use a match expression to handle both cases and print the result.

Running this code will output:

main.rs
The first character is h
25 chars
2 lines

gistlibby LogSnag