將輸出寫入字串

巨集 WITH-OUTPUT-TO-STRING 可用於建立字串輸出流,並在結尾返回結果字串。

(with-output-to-string (str)
  (write-line "Foobar!" str)
  (write-string "Barfoo!" str))
;=> "Foobar!
;   Barfoo!"

同樣可以使用 MAKE-STRING-OUTPUT-STREAMGET-OUTPUT-STREAM-STRING 手動完成。

(let ((str (make-string-output-stream)))
  (write-line "Foobar!" str)
  (write-string "Barfoo!" str)
  (get-output-stream-string str))