如何在Common Lisp中使用填充指针初始化字符串?

aka*_*nuk 5 string format common-lisp fill-pointer adjustable-array

我想在循环中使用格式化输出来生成字符串.手册说它可以通过给format函数一个带填充指针作为目标的字符串来轻松完成.不幸的是,手册中如何初始化此字符串并不透明.

我试着(string "")(format nil "")没有运气.

(make-array 0 :element-type 'character :fill-pointer 0) 对我有用,但感觉不对劲.

使用填充指针初始化字符串的正确方法是什么?

hua*_*uan 8

(make-array estimated-size-of-final-string
            :element-type 'character :fill-pointer 0)
Run Code Online (Sandbox Code Playgroud)

(:adjustable t如果估计不准确)也是一种方式; 为了累积输出以产生一个字符串,使用它可能更惯用with-output-to-string:

(with-output-to-string (stream)
  (loop repeat 8 do (format stream "~v,,,'-@A~%" (random 80) #\x)))

=>

"----------------------------------x
--------x
--------------------------------------x
----------------------------------------------------------------x
--------------x
-----------------------------------------x
---------------------------------------------------x
-----------------------------------------------------------x
"
Run Code Online (Sandbox Code Playgroud)


Vat*_*ine 6

(make-array 0 :element-type 'character :fill-pointer 0)是规范的方式(嗯,很可能使用初始非零长度并使用:initial-contents字符串值).也可以将fil指针值指定为t,将填充指针设置在字符串的末尾.


Rai*_*wig 6

使用FORMAT带有填充指针的字符串是一种非常少使用的功能.

CL-USER 125 > (let ((s (make-array 0
                                   :element-type 'character
                                   :adjustable t
                                   :fill-pointer t)))
                (format s  "Hello, ~a!" 'bill)
                s)
"Hello, BILL!"

CL-USER 126 > (describe *)

"Hello, BILL!" is an (ARRAY CHARACTER (12))
FILL-POINTER      12
0                 #\H
1                 #\e
2                 #\l
3                 #\l
4                 #\o
5                 #\,
6                 #\Space
7                 #\B
8                 #\I
9                 #\L
10                #\L
11                #\!
Run Code Online (Sandbox Code Playgroud)