我想在循环中使用格式化输出来生成字符串。手册说,通过给format
函数一个带填充指针作为目标的字符串,可以轻松完成。不幸的是,手册中如何初始化此字符串并不透明。
我试了(string "")
和(format nil "")
没有运气。
(make-array 0 :element-type 'character :fill-pointer 0)
对我有用,但感觉不对。
使用填充指针初始化字符串的正确方法是什么?
答案 0 :(得分:8)
(make-array estimated-size-of-final-string
:element-type 'character :fill-pointer 0)
(如果估算不准确,也带: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
"
答案 1 :(得分:6)
(make-array 0 :element-type 'character :fill-pointer 0)
是规范的方式(嗯,很可能使用初始的非零长度并使用:initial-contents
和字符串值)。也可以将fil指针值指定为t
,将填充指针设置在字符串的末尾。
答案 2 :(得分: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 #\!