Can I convert vec<vec<u8>> to string?

s is a string.
num_rows is a usize

let mut chars_list : Vec<Vec<u8>> = Vec::with_capacity(num_rows);
for (i, c) in s.chars().enumerate() {
    if some_rule {
        chars_list[i%some_value].push(c as u8);
    }
}
return std::str::from_utf8(chars_list.iter().fold(Vec::new(),|res, bs|{res.append(bs);res})).unwrap().to_string()

And I got an error, compiler told me the first parameter of fold should be &[u8], i tried, still don’t work

How about a flat_map?

Now your problem is Vec<u8> -> String

1 Like

glad to see you. thank you for helping me again… I will try it now.

You can use Iterator::flatten and Iterator::collect.

let v = vec![vec!['A', 'B'], vec!['A', 'B']];
let s: String = v.into_iter().flatten().collect();
1 Like


:tired_face:

Why do you push the characters as u8 into the vec?

I think it will be fast…

if you wanna keep Vec<Vec<u8>> instead of Vec<Vec<char>> then
you have to use map between flatten and collect

v.into_iter().flatten().map(|c| as char).collect()
1 Like

ok, let’s be fair here, first you make it work with elegant code. Next you benchmark it, and if then you think it’s slow, you figure out why and try to improve on it (but in the mean time you already have a working solution, and you can really evaluate how much time you want to invest in speeding it up), not the other way around.

You would be surprised sometimes with compilers optimizing things, it’s really not worth blindly complicating your life…

Don’t take my word for it, here is Donald Knuth:

Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%.

7 Likes

that’s right! thanks:grin:

c as u8 can only be correct if you’re working with ascii characters,if you have any unicode characters it will truncate the higher bits,returning a different character.

Here is a playground link to demonstrate:https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=6b410042a4a7218ea2cdfe879a154837

1 Like

thanks:grinning: