How can i join a vector of u8


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

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

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

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.

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

Playground link.


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


This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.