We can divide or split a string into two slices at a specified index by using the split_at()
method.
string.split_at(index)
string
: This is the string we want to slice.
index
: This is the index position, where the string should be sliced.
It returns two values. The first is a slice that starts from the first character of the string and ends in the index position specified. And the second slice starts from the string after the index position.
fn main() { // create some strings let str1 = "Edpresso"; let str2 = "Educative"; let str3 = "Rust"; let str4 = "Educative is the best platform!"; // split strings let (split1, split2) = str1.split_at(2); let (slice1, slice2) = str2.split_at(4); let (half1, half2) = str3.split_at(0); let (one, two) = str4.split_at(20); // print splitted strings println!("{} and {}",split1, split2); println!("{} and {}",slice1, slice2); println!("{} and {}",half1, half2); println!("{} and {}",one, two); }
str1
, str2
, str3
, str4
).split_at()
method and store them in new variables.RELATED TAGS
CONTRIBUTOR
View all Courses