6

I want to use formatted output in a loop to generate a string. Manual says it can be easily done by giving format function a string with a fill pointer as a destination. Unfortunately, it is not transparent from the manual how to initialize this string in the first place.

I tried (string "") and (format nil "") with no luck.

(make-array 0 :element-type 'character :fill-pointer 0) did work for me, but it just doesn't feel right.

What is the proper way to initialize a string with a fill pointer?

4

3 回答 3

9
(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
"
于 2013-08-07T11:40:01.450 回答
6

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

于 2013-08-07T08:21:00.600 回答
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                #\!
于 2013-08-07T12:25:21.667 回答