The easiest way to split a string in Rust is by making use of the split() function from the str type.
Example:
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);
}
}
Output:
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 |
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!