How to Split String in Rust

Nilesh Katuwal Feb 02, 2024
  1. Use the split() String Method in Rust
  2. Use the split_whitespace() Method in Rust
How to Split String in Rust

In this article, we’ll learn about the ways to split the string in Rust.

Use the split() String Method in Rust

The split () method returns an iterator over the substring of the string slice. They are separated by the characters, which are matched through the pattern.

The result cannot be stored for future use, with the split() method being one of its limitations. The collect() method can store the result returned by split() in the form of a vector.

Example Code:

fn main() {
   let words = "human,being,alive";

   for token in words.split(","){
      println!("token is {}",token);
   }

   println!("\n");
   let tokens:Vec<&str>= words.split(",").collect();
   println!("first_word is {}",tokens[0]);
   println!("second_word is {}",tokens[1]);
   println!("third_word is {}",tokens[2]);
}

The above example splits the string words whenever it finds a comma (,).

Output:

token is human
token is being
token is alive


first_word is human
second_word is being
third_word is alive

The below example uses the split() method to separate the strings based on the space. We can get the individual string as the method returns the iterator.

Example Code:

fn main() {
      let sentence = "This life can be amazing".split(" ");
      for s in sentence {
            println!("{}", s);
      }
}

Output:

This
life
can
be
amazing

Another use of it is to collect the separated strings into a vector with the use of Iterator::collect.

Example Code:

let sentence: Vec<&str> = "This life can be amazing".split(" ").collect();
 println!("{:?}", sentence);

The above code creates a vector with the separated strings as the individual elements.

Output:

["This" "life" "can" "be" "amazing"]

We can also use char::is_uppercase to separate the string available in the uppercase characters.

Example Code:

fn main() {
      let words: Vec<&str> = "peopleIhumansIlifeIenjoy".split(char::is_uppercase).collect();
      println!("{:?}", words);
}

Output:

["people" "human" "life" "enjoy"]

Use the split_whitespace() Method in Rust

The split_whitespace() is used to split the input string into different strings. Since it returns the iterator, we can iterate it through the token.

Example Code:

fn main(){
   let words = "Rust is a programming language".to_string();
   let mut i = 1;

   for token in words.split_whitespace(){
      println!("token {} {}",i,token);
      i+=1;
   }
}

Output:

token 1 Rust
token 2 is
token 3 a
token 4 programming
token 5 language

Related Article - Rust String