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
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
(map nil #'princ "bacon")
or
(loop for c across "bacon" do (princ c))
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")
t 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 © 2022 - 2024 — McMap. All rights reserved.
print
instead ofprinc
– Junji