How to Split a String in Rust

1. Overview

In this short tutorial, we’ll discuss how to split a string into two parts using Rust.

2. Using split_at()

split_at() method is part of the Rust standard library, it provides easy functionality to split strings at specific indexes.

2.1. Splitting String at Specific Index

To split a string at a specific index, we’ll pass the index to split_at() method. This splits the string into two parts. Here’s an example that split a string into two parts:

let word = "The dream my father told me";
let (first_part, second_part) = word.split_at(9);
assert_eq!(first_part, "The dream");
assert_eq!(second_part, " my father told me");

Here, we declare a variable of String type named word. Next, we create a slice to store the first and second parts of the word. Then, we invoke the split_at() method on the word and specify the index at which to split the sentence.

Notably, the whitespace is inclusive when counting the indexes.

Finally, we assert that the expected result is equal to returned parts.

Notably, the split_at() method only works with byte indices. In the case of multi-byte characters like emojis, it will panic. To prevent this, we can use the is_char_boundary() method to check if we are in a valid character boundary:

if word.is_char_boundary(9) {
    let (first_part, second_part) = word.split_at(9);
    println!("First part: {}", first_part);
    println!("Second part: {}", second_part);
} else {
     println!("Index {} is not a character boundary.", 9);

Here, we check if the index is within a valid character boundary before initiating a split.

2.2. Splitting String into Equal Halves

We can split a string in half by first calculating the midpoint. Let’s see an example code to split a string into halves:

let mid = word.char_indices().count() / 2;
let (first_half, second_half) = word.split_at(mid);
assert_eq!(first_half, "The dream my ");
assert_eq!(second_half, "father told me");

In the code above, we declare a variable mid to store the midpoint of a string. First, we convert the string to char indices and invoke the count() method on it to get the length of the string. Next, we divide the length by 2 to get the midpoint.

Additionally, we pass the midpoint to the split_at() which split the string at the midpoint.

3. Conclusion

In this article, we learned how to split a string by specifying an index to initiate the split. We also covered how to split a string in half by finding the midpoint.

The sources code for the examples is available on GitHub.