Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loop over characters in string, Common Lisp

How would I loop over the characters in a string of text in Common-lisp?

Here's what I want to do, but in Ruby:

string = "bacon"

string.each_char do |c|

    putc c

end
like image 796
Alexej Magura Avatar asked Aug 05 '13 19:08

Alexej Magura


2 Answers

(map nil #'princ "bacon")

or

(loop for c across "bacon" do (princ c))
like image 144
huaiyuan Avatar answered Nov 14 '22 09:11

huaiyuan


Looping over a string can be done using loop like so:

(let ((string "bacon")) 

   (loop for idex from 0 to (- (length string)) 1)
      do 
         (princ (string (aref string idex)) ) ))

;=> bacon
;=> NIL

To gather up the characters in string as a list use collect in the loop instead of do like so:

(let ((string "bacon")) 

   (loop for idex from 0 to (- (length string)) 1)
      collect 
         (princ (string (aref string idex)) ) ))

;=> bacon
;=> ("b" "a" "c" "o" "n")
like image 40
Alexej Magura Avatar answered Nov 14 '22 08:11

Alexej Magura