Appending character to string in Common Lisp
Asked Answered
M

2

9

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?

Munsey answered 4/8, 2013 at 17:53 Comment(0)
M
13

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!"
Motorboating answered 4/8, 2013 at 18:52 Comment(0)
D
8

If you want to extend a single string multiple times, it is often quite performant to use with-output-to-string, writing to the stream it provides. Be sure to use write or princ etc. (instead of format) for performance.

Delve answered 4/8, 2013 at 20:48 Comment(1)
or the obscure alternative, make sure that the FORMAT string can be compiled.Motorboating

© 2022 - 2024 — McMap. All rights reserved.