Common lisp 意外打印到字符串(通用lisp)
遵循和的文档 ,我希望以下各项能够发挥作用,他们确实做到了:Common lisp 意外打印到字符串(通用lisp),common-lisp,Common Lisp,遵循和的文档 ,我希望以下各项能够发挥作用,他们确实做到了: (print (with-output-to-string (sb nil) (format sb "~A " "hello, ") (format sb "~A~&" "world") sb)) (print (let ((sb (make-string-output-stream))) (format sb "~A " "hello, ") (format sb "~A~&" "
(print
(with-output-to-string (sb nil)
(format sb "~A " "hello, ")
(format sb "~A~&" "world")
sb))
(print
(let ((sb (make-string-output-stream)))
(format sb "~A " "hello, ")
(format sb "~A~&" "world")
(get-output-stream-string sb)))
但是,下面的示例与中的示例之一非常接近
,而不是:
(print
(with-output-to-string (sb (make-array
'(0)
:element-type 'base-char
:fill-pointer 0
:adjustable t))
(format sb "~A " "hello, ")
(format sb "~A~&" "world")
sb))
而是生成输出流本身,而不是保存在其中的字符串:
#<SB-IMPL::FILL-POINTER-OUTPUT-STREAM {1005FBE523}>
但我仍然会很感激找到一种方法来提取我第三个字符串
示例。请注意,返回值的方式有两种:
NIL
,则它将创建一个字符串并返回它(print
(with-output-to-string (sb (make-array ; creates a string
'(0)
:element-type 'base-char
:fill-pointer 0
:adjustable t))
(format sb "~A " "hello, ")
(format sb "~A~&" "world")
sb) ; you return the stream (which makes not much sense), but not the string
)
您已通过调用MAKE-ARRAY
创建了一个字符串。就在那里。使用它。为此,通常需要将其绑定到某个变量
如何返回字符串的示例:
(let ((s (make-array '(0)
:element-type 'base-char
:fill-pointer 0
:adjustable t)))
(with-output-to-string (sb s)
(format sb "~A " "hello, ")
(format sb "~A~&" "world"))
s)
或
在最后一种情况下,
with output to string
返回值,因为它得到一个字符串,用作输出的目标。有趣的是,在我的第一个示例中,我将nil
传递给,并将输出传递给string
,字符串和输出流以某种方式合并,因此,我可以使用变量sb
作为输出流(我从格式
向其发送输出)和字符串(我从外部表单返回)。@Reb.cain:如果不传递任何内容或不传递任何内容,则将返回字符串。如果传递字符串,将返回最后一个表单的值。在第一个示例中,sb的值被忽略。
(let ((s (make-array '(0)
:element-type 'base-char
:fill-pointer 0
:adjustable t)))
(with-output-to-string (sb s)
(format sb "~A " "hello, ")
(format sb "~A~&" "world"))
s)
(let ((s (make-array '(0)
:element-type 'base-char
:fill-pointer 0
:adjustable t)))
(with-output-to-string (sb s)
(format sb "~A " "hello, ")
(format sb "~A~&" "world")
s))