我怎样在Common Lisp中循环遍历文本字符串中的每个字符?
这是我想要用Ruby实现的功能:
string = "bacon"
string.each_char do |c|
putc c
end
我怎样在Common Lisp中循环遍历文本字符串中的每个字符?
这是我想要用Ruby实现的功能:
string = "bacon"
string.each_char do |c|
putc c
end
(map nil #'princ "bacon")
或者(loop for c across "bacon" do (princ c))
使用loop
可以遍历字符串,如下所示:
(let ((string "bacon"))
(loop for idex from 0 to (- (length string)) 1)
do
(princ (string (aref string idex)) ) ))
;=> bacon
;=> NIL
要将字符串string
中的字符作为列表收集,使用循环中的collect
而不是do
,如下:
(let ((string "bacon"))
(loop for idex from 0 to (- (length string)) 1)
collect
(princ (string (aref string idex)) ) ))
;=> bacon
;=> ("b" "a" "c" "o" "n")
print
而不是princ
。 - Alexej MaguraPRINC
可以打印字符。因此,“STRING”是浪费的。您还可以使用稍微更低级别的“WRITE-CHAR”。(("b" "a" "c" "o" "n")
)不是字符列表,而是字符串列表。 - Rainer Joswig