I'm in the process of learning Rust and came across this minor thing which seems more complicated than it ought to be. I want to create a string which contains a single character repeated N times.
The best I've come up with is this: (0..n).map({ |_| "X" }).collect::<Vec<_>>().concat()
This is a bit verbose, and it has to allocate a temporary vector which is sub-optimal.
Are there more concise, idiomatic, or efficient ways to do this?
If by "free" you mean "you paid that O(n) cost when loading the code from disk".
If it will happen once for a small vector that you might put in a constant, than the running time doesn't really matter. The running time only really matters if n is quite large, in which case, you would probably rather construct it at runtime only copying memory, rather than spending the time loading a huge array from disk, or if you will be doing this many times with different characters and lengths, in which you need a dynamic solution.
I had a use for a repeated character today and found this question. I wanted to center a title like this:
-------- My title --------
and began searching for how to easily repeat the - character. The above solutions would have worked fine, but I ended up with a slightly simpler solution using format!. When specifying a width, you can specify a custom fill character:
let formatted_title = format!("{:-^1$}", title, n);
This centers the title within a line of n- characters. Use {:-<1$} for left alignment, and {:->1$} for right alignment. The - can be any character you like. See the format! documentation for more information.
I hope this can come in handy for others who need to fill some empty space with a repeated character!