split and join
- Rust course
- Beginner
- Lesson 104/115
- 4 min
Split with split and join with join.
split and join
split divides text at a separator and returns an iterator yielding &str pieces. join combines a list of pieces into one text:
let csv = "elma, armut ,kiraz";
let parcalar: Vec<&str> = csv.split(',').map(|p| p.trim()).collect();
println!("{:?}", parcalar); // ["elma", "armut", "kiraz"]
println!("{}", parcalar.join(" | ")); // elma | armut | kirazThe pieces are slices of the source; nothing is copied. The source text must live as long as the pieces are used.
Other splitting methods
There are different splitting methods for different situations:
"bir iki\tüç".split_whitespace() // ["bir", "iki", "üç"]
"a\nb\nc".lines() // ["a", "b", "c"]
"anahtar=değer".split_once('=') // Some(("anahtar", "değer"))
"a-b-c-d".splitn(2, '-') // ["a", "b-c-d"]
"a-b-c".rsplit('-') // ["c", "b", "a"]split_whitespace treats several spaces and tabs as one separator; it's the safest for user input.
Practice CSV line
Split the text let csv = "elma, armut ,kiraz"; into pieces with split(',') and trim, and collect them into a Vec<&str>. Print the vector with {:?} and the result of join(" | "), separated by a space.
Starter code
fn main() {
// buraya yaz
}Sample solution
fn main() {
let csv = "elma, armut ,kiraz";
let parcalar: Vec<&str> = csv.split(',').map(|p| p.trim()).collect();
println!("{:?} {}", parcalar, parcalar.join(" | "));
}Expected output
["elma", "armut", "kiraz"] elma | armut | kiraz
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is <code>"a,,b".split(',').count()</code>?
- 3 ("a", "", "b") Correct answer
- 2
- 4
- 1
Explanation: An empty piece appears between two consecutive separators. Use filter(|p| !p.is_empty()) to drop empty ones.
2 Join the pieces
let p = vec!["a", "b", "c"];
let s = p.____("-"); // "a-b-c"
let p = vec!["a", "b", "c"];
let s = p.join("-"); // "a-b-c"
Explanation: join combines the pieces with the given separator between them.
3 Method and result
| Term | Meaning |
|---|---|
"a b c".split_whitespace().count() |
3 |
"a,b".split(',').count() |
2 |
"x=1".split_once('=') |
Some(("x", "1")) |
["a", "b"].join("+") |
"a+b" |