Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
A simple defun to split a space separated string into individual word strings. "one two three" into ("one" "two" "three") so to say.
(defun split-sentence-to-words (sentence)
(let ((word '()))
(loop for ch across sentence
if (member ch '(#\space #\tab #\,))
collect (coerce (reverse word) 'string) into words and do (setf word '())
do (push ch word)
finally (return (append words (coerce (reverse word) 'string))))))
Copy link

abishek commented Aug 9, 2020

@RainerJoswig on twitter helped me out:

Here is my fixed version taking inspiration from his sample.

(defun create-word (chars)
  (coerce (reverse chars) 'string))

(defun split-sentence-to-words (sentence &optional (separators '(#\space #\tab #\,)))
  (let ((chars '()))
     (loop for ch across sentence
           if (member ch separators)
             if chars collect (create-word chars) and do (setf chars '()) end
               else do (push ch chars))
     (if chars (list (create-word chars))))))

Yes, I could copy the aux and the flet. But these are things I am not super familiar with. So I'll stick to what I know until I grow up some more. But the real trick I needed was where the append is used.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment