问题描述
我正在尝试接受用户输入并将其存储在列表中,而不仅仅是扫描由单个字符串组成的列表,我希望扫描的每个单词都成为其自己的字符串.示例:
I'm trying to take user input and storing it in a list, only instead of a list consisting of a single string, I want each word scanned in to be its own string.Example:
> (input)
This is my input. Hopefully this works
将返回:
("this" "is" "my" "input" "hopefully" "this" "works")
请注意,我不想在最终列表中添加空格或标点符号.
Taking note that I don't want any spaces or punctuation in my final list.
任何输入将不胜感激.
推荐答案
split-sequence
是现成的-货架解决方案.
split-sequence
is the off-the-shelf solution.
您也可以自己滚动:
(defun my-split (string &key (delimiterp #'delimiterp))
(loop :for beg = (position-if-not delimiterp string)
:then (position-if-not delimiterp string :start (1+ end))
:for end = (and beg (position-if delimiterp string :start beg))
:when beg :collect (subseq string beg end)
:while end))
其中delimiterp
检查您是否要分割此字符,例如
where delimiterp
checks whether you want to split on this character, e.g.
(defun delimiterp (c) (or (char= c #\Space) (char= c #\,)))
或
(defun delimiterp (c) (position c " ,.;/"))
PS.在查看预期的返回值时,您似乎想在my-split
之前调用 string-downcase
PS. looking at your expected return value, you seem to want to call string-downcase
before my-split
.
PPS.您可以轻松地修改my-split
以接受:start
,:end
,:delimiterp
& c.
PPS. you can easily modify my-split
to accept :start
, :end
, :delimiterp
&c.
PPPS.抱歉my-split
的前两个版本中的错误.请考虑一种指标,该指标表明不应使用该功能的自己的版本,而应使用现成的解决方案.
PPPS. Sorry about bugs in the first two versions of my-split
. Please consider that an indicator that one should not roll one's own version of this function, but use the off-the-shelf solution.
这篇关于Lisp-将输入拆分为单独的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!