如何使用clisp将字符串转换为列表?

时间:2011-09-18 04:36:42

标签: lisp common-lisp

如何将字符串"1 2 3 4 5 6 7"优雅地转换为列表(1 2 3 4 5 6 7)?我正在使用CLISP。

7 个答案:

答案 0 :(得分:3)

您应该在循环中使用parse-integer

例如,使用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)

如果您需要更好地控制拆分,请使用split-sequencecl-ppcre库。

如果您需要解析更多通用数字格式,请使用parse-number库。

可以从Quicklisp获得库。

答案 1 :(得分:2)

提示:看看with-input-from-string

答案 2 :(得分:2)

(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)

它有效但我觉得它不是那么优雅,因为有许多read电话。

再次感谢!

答案 3 :(得分:2)

这是一个递归解决方案。

    ;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)))

答案 4 :(得分:1)

我看到斯万特是对的。我之前的尝试没有奏效。这是另一种尝试。我使用concatenate将字符串更改为列表表示形式。然后我使用read-from-string将字符串(s-2)转换为实际列表。

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

我把它变成这样的函数:

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

"让"的唯一目的和" L"是使函数from-string-to-list仅返回列表而不返回多个值。 read-from-string返回两个值:我认为列表和字符串的大小。

答案 5 :(得分:0)

那样做,

(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)))

答案 6 :(得分:0)

我认为这可行:

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

这会生成一个以空格为元素的列表。删除空格:

(setf L-final (remove #\Space L-temp))
相关问题