gpt4 book ai didi

lisp - 如何在拆分字符串后修剪以在 Lisp 中列出

转载 作者:太空宇宙 更新时间:2023-11-03 18:57:06 25 4
gpt4 key购买 nike

以下代码来自 https://www.rosettacode.org/wiki/Tokenize_a_string#Common_Lisp在逗号处拆分字符串并发送列表。

(defun comma-split (string)
(loop for start = 0 then (1+ finish)
for finish = (position #\, string :start start)
collecting (subseq string start finish)
until (null finish)
)
)

但是,如果子字符串在原始字符串中,则子字符串周围会有空格。

> (comma-split " a, b ,c , d ,   e")
(" a" " b " "c " " d " " e")

如何在此处添加字符串修剪功能以删除这些空格。我看不到函数中返回的字符串变量。

我尝试使用局部变量,但它不起作用:

(defun comma-split2 (string)
(let* ( (onestr "")
)
(loop for start = 0 then (1+ finish)
for finish = (position #\, string :start start)
(onestr (subseq string start finish))
(onestr (string-trim onestr))
collecting onestr
until (null finish)
)
))

加载文件时出错:

*** - LOOP: illegal syntax near (ONESTR (SUBSEQ STRING START FINISH)) in
(LOOP FOR START = 0 THEN (1+ FINISH) FOR FINISH = (POSITION #\, STRING :START START) (ONESTR (SUBSEQ STRING START FINISH))
(ONESTR (STRING-TRIM ONESTR)) COLLECTING ONESTR UNTIL (NULL FINISH))
The following restarts are available:

即使在第二个函数中修剪 outlist 也不起作用:

(defun comma-split2 (string)
(let ( (outlist (list))
(setf outlist (comma-split string))
(dolist (str outlist)
(push (string-trim str) outlist)
)
(nreverse outlist)
)))

> (comma-split2 " a, b ,c , d , e")

*** - LET: illegal variable specification (SETF OUTLIST (COMMA-SPLIT STRING))
The following restarts are available:

最佳答案

COLLECTING 语句是创建列表的内容。因此,您需要围绕正在收集的内容调用 STRING-TRIM

(defun comma-split (string)
(loop for start = 0 then (1+ finish)
for finish = (position #\, string :start start)
collecting (string-trim " " (subseq string start finish))
until (null finish)))

您不应该将右括号单独放在一行。

关于lisp - 如何在拆分字符串后修剪以在 Lisp 中列出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38259699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com