What is the string.split() method in Rust?

Overview

With the split() method, we can create an iterator containing the particular string's sub-strings. This method takes the separator as an argument. This separator determines where to start splitting the strings to an iterator of its sub-strings.

Syntax

string.split(separator)
Syntax for split() method of a string in Rust

Parameters

  • string: This is the string we want to split.
  • separator: This is the separator we specify. Wherever this separator is found in the string, that is where splitting occurs.

Return value

The value returned is an iterator that contains the sub-strings of the split strings.

Code

fn main() {
// create some strings
let str1 = "Rust|is|the|best!";
let str2 = "Educative&is&the&online&learning&platform!";
let str3 = "Welcome to Edpresso!";
let str4 = "225.225.22.128";
// create some separators
let sep1 = "|";
let sep2 = "&";
let sep3 = " "; // whitespace
let sep4 = ".";
// split the strings and print each substring
println!("The substrings in {} are:", str1);
for substring in str1.split(sep1) {
println!("{}", substring);
}
// split the strings and print each substring
println!("\nThe substrings in {} are:", str2);
for substring in str2.split(sep2) {
println!("{}", substring);
}
// split the strings and print each substring
println!("\nThe substrings in {} are:", str3);
for substring in str3.split(sep3) {
println!("{}", substring);
}
// split the strings and print each substring
println!("\nThe substrings in {} are:", str4);
for substring in str4.split(sep4) {
println!("{}", substring);
}
}

Explanation

  • Line 3–6: We create some strings.
  • Lines 9–12: We create some separators which will be used for splitting the strings.
  • Lines 16, 22, 28, and 34: We split the strings based on the separator specified. Then we loop the iterator returned, using the for in loop, and print the results to the console screen.

Free Resources