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 |
-
Facing issues? Have Questions? Post them here! I am happy to answer!
More Posts related to Rust,
- Rust: Cargo Init vs Cargo New Command
- Rust: Write and Run Hello World! Program Example
- How to Split a String using Rust Language
- How to Sort a Vector in Rust with Examples
- Fix: error: could not find `Cargo.toml` in Users or any parent directory
- How to uninstall Rust Language from Mac/Linux/Ubuntu
- How to update Cargo (Rust Lang)
- Fix: rust-analyzer failed to discover workspace [Visual Studio Code]
- How to install Rust using rustup on macOS/Linux/Ubuntu
- Cargo Watch: To Recompile Rust Project Automatically
- Difference between rustc and cargo build commands
- How to Split a String by Space in Rust
- How to know Rust is Installed on Mac?
- Rust: zsh: no such file or directory: ./main
- How to update Rust on Mac/Linux
- List of Rust Cargo Commands
- How to find version of Cargo in Rust
- Fix: error: mismatched closing delimiter } [Rust]
More Posts:
- Program 2: Print your name using print() function - 1000+ Python Programs - Python-Programs
- How to Display content of a file in Terminal Screen? - Linux
- [Eclipse] Locate Preferences in macOS - MacOS
- Difference between rustc and cargo build commands - Rust
- Java 8: Find the Max value in a List - Java
- Python: How to add Progress Bar in Console with Examples - Python
- Find Java JRE Installation location Mac OS X - Mac-OS-X
- Mac: Change Screenshot Location - MacOS