String Slicing#
String Slicing Syntax#
Rust provides convenient syntax for slicing strings.
Let’s explore this through the following code.
fn main() {
let s = String::from("hello world");
println!("{}", &s[0..5]);
println!("{}", &s[6..11]);
println!("{}", &s[..5]);
println!("{}", &s[6..]);
println!("{}", &s[..]);
}By coding &s[0..5], you can slice out "hello".
Here, 0 means the start index, and 5 means the end index + 1.
(Note that you use the end index + 1.)
By coding &s[6..11], you can slice out "world".
Also, if you omit the start index, it points to the first element, and if you omit the end index, it points to the last element.
By coding &s[..5], omitting the start index slices from the beginning to index 4, resulting in "hello".
By coding &s[6..], omitting the end index slices from index 6 to the last element, resulting in "world".
You can also omit both the start and end indexes, as in &s[..].
The [..] syntax can be used with all collections, such as integer and float types#
The [..] syntax is not only available for String types.
It can be used with various types that make up a collection.
Let’s look at the following example.
fn main() {
let a = [1, 2, 3, 4, 5];
let b = &a[1..3]; // --> b = [2, 3]
println!("{}, {}", b[0], b[1]);
let c = &a[..3];
let d = &a[2..];
let e = &a[..];
}a is an array of i32-type elements, and the same [..] syntax can be used with it.
By coding &a[1..3], you extract [2, 3] from index 1 to index 2.
Just like the String slice explained earlier, you can omit the start, end, or both indexes.