在字符串中循环遍历字符,通用Lisp。

11

我怎样在Common Lisp中循环遍历文本字符串中的每个字符?

这是我想要用Ruby实现的功能:

string = "bacon"

string.each_char do |c|

    putc c

end
2个回答

34
(map nil #'princ "bacon")
或者
(loop for c across "bacon" do (princ c))

3

使用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 Magura
13
无需从长度中减去1。使用“BELOW”。 实际上,在循环中不需要索引来迭代整个字符串。使用“ACROSS”。此外,将字符转换为字符串没有意义。PRINC可以打印字符。因此,“STRING”是浪费的。您还可以使用稍微更低级别的“WRITE-CHAR”。(("b" "a" "c" "o" "n"))不是字符列表,而是字符串列表。 - Rainer Joswig
@RainerJoswig,我不认为我曾经说过它返回一个字符列表--我说过它会将字符收集到一个列表中,但这并不一定意味着它将它们作为字符存储。我只是意味着它们被单独处理了。 - Alexej Magura

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接