Repeat string/character with (format)
common-lisp, string-formatting
Solution
(defun write-repeated-string (n string stream)
(loop repeat n do (write-string string stream)))
(write-repeated-string 5 "hi" *standard-output*))
Generally you can use the format iteration:
(format t "~v@{~A~:*~}" 5 "hi")
`~A` can output all kinds of items, not just characters. For more information see uselpa's linked answers.
Above takes the iteration number from the first argument. Thus the `v` behind the tilde.
The rest of the arguments will be consumed by the iteration. Thus the `@`.
Inside the iteration we go back one element. Thus `~:*`.
It's similar to `(format t "~v{~A~:*~}" 5 '("hi"))`, which might be simpler to understand.
Problem
Is there a repeat directive for `(format)` in Common lisp, something like(I know this won't work): ``` (format t "~5C" #\*) ``` Just wondering if there isn't a more elegant way to do it than this:(from rosettacode ) ``` (defun repeat-string (n string) (with-output-to-string (stream) (loop repeat n do (write-string string stream)))) (princ (repeat-string 5 "hi")) ```