In Rust, you can use array-like indexing or the chars()
method to get the first character of a string.
In this example,
str
with a value of "Hello World"
.0
on the string str
or the chars()
method and nth(0)
to get the first character.fn main() {
let str = "Hello World";
let first_char = str.chars().nth(0).unwrap();
println!("First character: {}", first_char);
}
First character: H
In this example,
str
with a value of "apple"
.0
on the string str
or the chars()
method and nth(0)
to get the first character.fn main() {
let str = "apple";
let first_char = str.chars().nth(0).unwrap();
println!("First character: {}", first_char);
}
First character: a
In this tutorial, we learned How to get First Character in String in Rust language with well detailed examples.