How to convert a string to a list using clisp?

How to convert the string "1 2 3 4 5 6 7" to a list (1 2 3 4 5 6 7) elegantly? I am using CLISP.

+6
source share
7 answers

Hint: take a look at c-input-from-string .

+3
source

You must use parse-integer in a loop.

For example, using loop :

 (let ((string "1 2 3")) (loop :for (integer position) := (multiple-value-list (parse-integer string :start (or position 0) :junk-allowed t)) :while integer :collect integer)) 

→ (1 2 3)

If you need better control over splitting, use the split-sequence library or cl-ppcre .

If you need to analyze more general number formats, use the parse-number library.

Libraries are available from Quicklisp.

+3
source
 (with-input-from-string (s "1 2 3 4 5 6 7" :index i :start 0 :end 13) (list (read s) (read s) (read s) (read s) (read s) (read s))) (1 2 3 4 5 6 7) 

it works, but I feel that it is not as elegant as there are many read calls.

Thanks again!

+2
source

Here is a recursive solution.

  ;Turns a string into a stream so it can be read into a list (defun string-to-list (str) (if (not (streamp str)) (string-to-list (make-string-input-stream str)) (if (listen str) (cons (read str) (string-to-list str)) nil))) 
+2
source

I see that Svante is right. My previous attempt did not work. Here is another try. I use concatenate to change a string in a list view. Then I use read-from-string to convert the string (s-2) to the actual list.

 (setf s-0 "1 2 3 4 5 6 7") (setf s-1 (concatenate 'string "(" s ")" )) (setf s-2 (read-from-string s-1)) 

I will pass it into a function like this:

 (defun from-string-to-list (s) (let ((L (read-from-string (concatenate 'string "(" s ")")))) L)) 

The sole purpose of "let" and "L" is to make the from-string-to-list function return only a list and not return multiple values. read-from-string returns two values: list and string size, I think.

+1
source

It will be done

 (with-input-from-string (s "1 2 3 4 5") (let ((r nil)) (do ((line (read s nil 'eof) (read s nil 'eof))) ((eql line 'eof)) (push line r)) (reverse r))) 
0
source

I think this might work:

 (setf s "1 2 3 4 5 6 7") (setf L-temp (coerce s 'list)) 

This makes a list with spaces as elements. Remove spaces:

 (setf L-final (remove #\Space L-temp)) 
0
source

Source: https://habr.com/ru/post/897555/


All Articles