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!
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
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:
- Fix: incompatible types: Object cannot be converted to Integer - Java
- How to Enable spellcheck Notepad++ - NotepadPlusPlus
- How to declare and initialize Array in Java Programming - Java
- How to insert date, time or custom timestamp in Notepad++ - NotepadPlusPlus
- Online Regex Tester Tool - Tools
- All directional arrows codes for HTML - Html
- Find the location of Spotlight searched file - Mac-OS-X
- Batch updates + Prepared Statement with Spring Boot 3 + JDBC - Java