How to Split a String using Rust Language

The easiest way to split a string in Rust is by making use of the split() function from the str type.


    fn main() {
     let data_str = "This is some data|I want to split|Based on Pipe";
     let delimiter = "|";
     let let_split_data: Vec<&str> = data_str.split(delimiter).collect();
     for element in let_split_data {
            println!("{}", element);
    This is some data
    I want to split
    Based on Pipe

    There are some more built-in functions that you can use with certain types of delimiters.

    Method Description Doc Link
    split() Splits a string based on the privded custom delimiter split
    split_whitespace() Splits a string by whitespace characters split_whitespace
    split_terminator() Splits a string by a given delimiter, excluding the last delimiter if the end of the string split_terminator
    splitn() Splits a string into a specified number of substrings splitn

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:

Copyright ยฉ Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap