How to split a string into two in Rust

Overview

We can divide or split a string into two slices at a specified index by using the split_at() method.

Syntax

string.split_at(index)
Syntax for split_at() method in Rust

Parameters

string: This is the string we want to slice.

index: This is the index position, where the string should be sliced.

Return values

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.

Example

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);
}

Explanation

  • Lines 3–6: We create some strings (str1, str2, str3, str4).
  • Lines 9–12: We split the strings using the split_at() method and store them in new variables.
  • Lines 15–18: We print out the slices of the strings.

Free Resources