How can i join a vector of u8

Hi,

if i have a vector of type Vec<u8> how can i join it's values?

example: [1, 2, 3, 4] join with '.' => "1.2.3.4"

This is what I got. I would also be interested in a better way though.

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=13fdcc998026fe5eb5a9c0aba13d7407

1 Like

I believe there's two steps to your question. First the numbers need to be converted to strings. Second you want a new string with a separator between the strings from the first step.

Here's my quick attempt:

fn join_nums(nums: &[u8], sep: &str) -> String {
    // 1. Convert numbers to strings
    let str_nums: Vec<String> = nums.iter() 
        .map(|n| n.to_string())  // map every integer to a string
        .collect();  // collect the strings into the vector
    
    // 2. Join the strings. There's already a function for this.
    str_nums.join(sep)
}

fn main() {
    let nums = vec![1u8, 2, 3, 4];
    println!("{}", join_nums(&nums, "."));
}

Playground link.

2 Likes

For the special case where you know the number of elements and the separator at compile-time (for example, if you are always formatting a "dotted quad" IPv4 address) then you use an array instead of a vector, and a compile-time formatting string:

fn join_nums(nums: [u8; 4]) -> String {
    format!("{}.{}.{}.{}", nums[0], nums[1], nums[2], nums[3])
}

fn main() {
    let nums = [1u8, 2, 3, 4];
    println!("{}", join_nums(nums));
}
1 Like

Can also just use https://docs.rs/itertools/0.8.0/itertools/fn.join.html

2 Likes