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

Overview

The split_whitespace() method of a string in Rust splits a string into sub-strings at whitespace. This means it will slice the string into multiple sub-strings at every whitespace.

Syntax

string.split_whitespace()
The syntax for the split_whitespace() method

Parameters

string: This is the string we want to split into sub-strings.

Return value

The value returned is an iterator containing the sliced sub-strings.

Example

fn main() {
// create some strings
let str1 = "Rust is very interesting";
let str2 = "Educative is the best";
// print substrings of string
println!("The substrings without whitespaces in '{}' are:", str1);
for byte in str1.split_whitespace() {
println!("{}", byte);
}
// print substrings of string
println!("\nThe substrings without whitespaces in '{}' are:", str2);
for byte in str2.split_whitespace() {
println!("{}", byte);
}
}

Explanation

  • Lines 3–4: We create some strings.
  • Lines 8–14: We get the sub-strings of each string with the split_whitespace() method. We print each string using the for in loop.

Free Resources