loop over characters in string, Common Lisp
Asked Answered
J

2

12

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
Junji answered 5/8, 2013 at 19:20 Comment(0)
P
35
(map nil #'princ "bacon")

or

(loop for c across "bacon" do (princ c))
Procambium answered 5/8, 2013 at 19:48 Comment(0)
J
3

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")
Junji answered 5/8, 2013 at 19:20 Comment(3)
you could also use print instead of princJunji
You dont need to subtract 1 from the length. Use BELOW. You actually don't need an index in LOOP to iterate over a string at all. Use ACROSS. Also converting a character to a string does not make sense. PRINC` can print characters. Thus STRING is a waste. You can also use WRITE-CHAR, which is slightly more low-level. ("b" "a" "c" "o" "n") is also not a list of characters. It is a list of strings.Combes
@RainerJoswig I don't think that I ever said that it returned a list of characters--I said that it gathered up the characters in a list, but that doesn't necessarily mean that it stored them as characters. I just meant that they were processed individually.Junji

© 2022 - 2024 — McMap. All rights reserved.