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: Rakesh
Author Info:

Rakesh is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

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