Appending character to string in Common Lisp
character, common-lisp, lisp, string
Solution
If the string has a fill-pointer and maybe is also adjustable.
Adjustable = can change its size.
fill-pointer = the content size, the length, can be less than the string size.
`VECTOR-PUSH` = add an element at the end and increment the fill-pointer.
`VECTOR-PUSH-EXTEND` = as `VECTOR-PUSH`, additionally resizes the array, if it is too small.
We can make an adjustable string from a normal string:
CL-USER 32 > (defun make-adjustable-string (s)
(make-array (length s)
:fill-pointer (length s)
:adjustable t
:initial-contents s
:element-type (array-element-type s)))
MAKE-ADJUSTABLE-STRING
`VECTOR-PUSH-EXTEND` then can add characters to the end of the string. Here we add the character `#\!` to the end of the string `"Lisp"`. The result string then is `"Lisp!"`:
CL-USER 33 > (let ((s (make-adjustable-string "Lisp")))
(vector-push-extend #\! s)
s)
"Lisp!"
Problem
I have a character `ch` that I want to append to a string `str`. I realize you can concatenate strings like such: ``` (setf str (concatenate 'string str (list ch))) ``` But that seems rather inefficient. Is there a faster way to just append a single character?