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
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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Oct 21, 2024 (edit).