Join
In Rust, consider a string
vector that contains strings. We can join these string
elements together into a single descriptive string
.
With a delimiter string
, we can place characters in between the elements in the resulting string
. Any string
can be used as a delimiter.
Here we have a string
array of just 2 elements. The type of the array is implicit here, but it could be specified with more syntax.
string
.fn main() { // Create an array of strings. let patterns = ["abc", "def"]; // Join together the results into a string. let result = patterns.join(","); println!("JOIN: {}", result); }JOIN: abc,def
String
vectorIn Rust, join()
acts upon a slice. And a string
array, string
slice, or string
vector can be used as a slice—no special conversions are needed.
string
, and print it.fn main() { let mut landmarks = vec!["mountain", "hill"]; landmarks.push("valley"); landmarks.push("river"); // Join the string vector on another string. // ... Two characters can be used. let result = landmarks.join("++"); println!("JOIN: {}", result); }JOIN: mountain++hill++valley++river
Split
and joinConceptually, split()
and join()
are opposites—they separate and merge string
elements. We demonstrate this by using split, then join()
, to get the original string
.
split()
we place the letters into a Vec
, and then we call join with the same delimiter to go back to the original data.fn main() { let input = "a b c"; // Split on space into a vector. let v: Vec<_> = input.split(' ').collect(); // Join with space to get the original string back again. let j = v.join(" "); // Test result. if input == j { println!("SPLIT-JOIN ROUNDTRIP OK: {}/{}", input, j); } }SPLIT-JOIN ROUNDTRIP OK: a b c/a b c
Join
is useful in many Rust programs, and an obsolete connect()
method has the same effect as join. Join
and split can be used together for full round-trip parsing.