THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.
This tutorial shows you multiple ways to split a string with a separator.
There are multiple ways we can do it.
split
function in String object split the string using a pattern, returns an iterator.
The split
method split a string into multiple slices using spaces, separators or characters
You can use for in loop to iterate the result or you can convert it to Vec<&str>
using the collect method.
fn main() {
let name = "Hello John";
for item in name.split(" ") {
println!("{}", item);
}
let items: Vec<&str> = name.split(" ").collect();
println!("{}", items[0]);
println!("{}", items[1]);
}
Output:
Hello
John
Hello
John
split_whitespace function
split_whitespace
function returns the iterator by splitting the string with the whitespace separator.
Here is an example program
fn main() {
let name = "Hello John";
for item in name.split_whitespace() {
println!("{}", item);
}
let items: Vec<&str> = name.split_whitespace().collect();
println!("{}", items[0]);
println!("{}", items[1]);
}
🧮 Tags
Recent posts
Ways to skip test case execution in Gradle project build Learn Gradle | tutorials, and examples How to run only single test cases with Gradle build How to print dependency tree graph in Gradle projects How to perform git tasks with build script?Related posts