In Rust, you can use string slicing to get the first N characters from a string.
In this example,
str
with a value of "Hello World"
.&str[0..5]
to get the first 5 characters.fn main() {
let str = String::from("Hello World");
let first5Chars = &str[0..5];
println!("First 5 characters of the string are: {}", first5Chars);
}
First 5 characters of the string are: Hello
In this example,
str
with a value of "apple"
.&str[0..3]
to get the first 3 characters.fn main() {
let str = String::from("apple");
let first3Chars = &str[0..3];
println!("First 3 characters of the string are: {}", first3Chars);
}
First 3 characters of the string are: app
In this tutorial, we learned How to get First N Characters in String in Rust language with well detailed examples.