How to Split a String by Space in Rust


We can split a String in Rust based on spaces by making use of the split_whitespace() method.

The split_whitespace() method returns an iterator which can be collect as Vec<&str> using the collect() method.

Example:
fn main() {
    
    let data_string = "This is my String that I want to Split";
    let splitted_str: Vec<&str> = data_string.split_whitespace().collect();

    for word in splitted_str {
        println!("{}", word);
    }
}
Output:
This
is
my
String
that
I
want
to
Split
How to Split a String in Rust

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap