I'm working with hexadecimal strings and I want to insert a space between every two characters in a string so that each byte can be easily distinguished.
let hex = "FF6A1E0A";
// Desired output: "FF 6A 1E 0A"
I'm aware that chunks
and join
could be used, but no such methods are available in Chars
.
How can I insert spaces (and to that extent, any character) at every nth character in a string and what, if any performance considerations should be taken into account?
Chars
implements Iterator
, meaning it does not provide a chunks
method.
While you can coerce Chars
into a vector of chars, chunk it, collect, and so on...
text.chars()
.collect::<Vec<char>>()
.chunks(n)
.map(|c| c.iter().collect::<String>())
.collect::<Vec<String>>()
.join(" ");
This is very inefficient as it involves allocating and reallocating multiple vectors and String
s along the way.
Instead, you should take advantage of enumerate
and flat_map
like so...
text.chars()
.enumerate() // Give us access to the current index, `i`, and the next value, `c`.
.flat_map(|(i, c)| {
if i != 0 && i % n == 0 {
Some(' ')
} else {
None
}
.into_iter()
.chain(std::iter::once(c))
})
.collect::<String>()
Where n
equals your desired insert interval (in your hex example this would be 2). This only has to allocate the final resultant String
, staying as iterators until then.