Join. In Rust, consider a string vector that contains strings. We can join these string elements together into a single descriptive string.
Delimiter info. With a delimiter string, we can place characters in between the elements in the resulting string. Any string can be used as a delimiter.
First example. 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.
Info With join, we place a comma character in between the 2 elements in the array. The result is a single 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 vector. In 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.
Here We join the strings in a vector of terrain landmarks. We use a 2-character delimiter for the output 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 join. Conceptually, split() and join() are opposites—they separate and merge string elements. We demonstrate this by using split, then join(), to get the original string.
Detail With 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
A summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Feb 27, 2022 (edit).