I'm attempting to learn Rust. And a recent problem I've encountered is the following:
given a String
, that is exactly some multiple of n, I want to split the string into chunks of size n, and insert a space in between these chunks, then collect back into a single string.
The issue I was running into, is that the chars()
method returns the Chars
struct, which for some reason doesn't implement the SliceConcatExt
trait, so chunks()
can't be called on it.
Furthermore, once I've successfully created a Chunks struct (by calling .bytes()
instead) I'm unsure how to call a .join(' ')
since the elements are now Chunks
of byte slices...
There has to be an elegant way to do this I'm missing.
For example here is an input / output that illustrates the situation:
given: whatupmyname, 4
output: what upmy name
This is my poorly written attempt:
let n = 4;
let text = "whatupmyname".into_string();
text.chars()
// compiler error on chunks() call
.chunks(n)
.collect::<Vec<String>>()
.join(' ')