To get a character at a specific index in a string in Rust, you can use array-like indexing or the []
operator.
In this example,
str
with a value of "Hello World"
.[]
operator on the string str
.fn main() {
let str = String::from("Hello World");
let char_at_index_3 = str.chars().nth(3).unwrap();
println!("Character at index 3: {}", char_at_index_3);
}
Character at index 3: l
In this example,
str
with a value of "Rust"
.[]
operator on the string str
.fn main() {
let str = String::from("Rust");
let char_at_index_1 = str.chars().nth(1).unwrap();
println!("Character at index 1: {}", char_at_index_1);
}
Character at index 1: u
In this tutorial, we learned How to get Character at Specific Index in String in Rust language with well detailed examples.