我有一个带有条件的循环,根据该循环,我决定是否应该向现有字符串添加内容。在Python中,它应该看起来像(这是虚拟代码,只是为了显示这个想法):
…
字符串连接依赖于更一般的 CONCATENATE 功能:
CONCATENATE
(concatenate 'string "a" "b") => "ab"
由于它被一些人认为是冗长的,你可以找到实现更短版本的库:
(ql:quickload :rutils) (import 'rutils:strcat)
然后:
(strcat "a" "b")
要分配和增长字符串,您需要使用 SETF 使用现有变量。
SETF
(let ((string "")) (dotimes (i 5) (when (evenp i) (setf string (strcat string (princ-to-string i))))) string)
Lisp中更惯用的方法是避免字符串连接,但是在写入缓冲区的流中打印。
(with-output-to-string (stream) ;; now, stream is bound to an output stream ;; that writes into a string. The whole form ;; returns that string. (loop for i from 0 below 5 by 2 do (princ i stream))) => "024"
在上面, stream 只是用于命名流的符号,您可以使用任何其他符号,包括 *standard-output* ,表示当前输出流的特殊变量。这样做会使封闭的代码将其标准输出重定向到字符串流。
stream
*standard-output*
构建中间列表的另一种方法是: iota 是一个小实用程序 亚历山大 图书馆:
iota
(delete-if #'oddp (alexandria:iota 5)) => (0 2 4)
为了产生一个字符串,你也可以使用 FORMAT ,它有一个可以迭代列表的指令:
FORMAT
(format nil "~{~a~}" '(0 2 4)) => "024"
该 nil stream destination表示字符串目标,意思是 (format nil ...) 返回一个字符串。每个指令都以波形符开头( ~ ) ~{ 和 ~} 包含迭代指令;在那个街区里面, ~a 打印“美学上”的值(不可读)。
nil
(format nil ...)
~
~{
~}
~a