Lisp - 将输入拆分为单独的字符串

Sea*_*ans 16 lisp string split input list

我正在尝试将用户输入并将其存储在列表中,而不是仅包含单个字符串的列表,我希望扫描的每个单词都是自己的字符串.例:

> (input)
This is my input. Hopefully this works
Run Code Online (Sandbox Code Playgroud)

会回来:

("this" "is" "my" "input" "hopefully" "this" "works")
Run Code Online (Sandbox Code Playgroud)

请注意我在最终列表中不需要任何空格或标点符号.

任何投入将不胜感激.

sds*_*sds 20

split-sequence 是现成的解决方案.

你也可以自己动手:

(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))
Run Code Online (Sandbox Code Playgroud)

在那里delimiterp检查是否要拆就这个人物,如

(defun delimiterp (c) (or (char= c #\Space) (char= c #\,)))
Run Code Online (Sandbox Code Playgroud)

要么

(defun delimiterp (c) (position c " ,.;/"))
Run Code Online (Sandbox Code Playgroud)

PS.看着你期望的回报值,你似乎想要string-downcase之前打电话my-split.

PPS.你可以很容易地修改my-split接受:start,:end,:delimiterp&C.

购买力平价.对于前两个版本的错误抱歉my-split.请考虑一个指标,即应该使用此功能的自己版本,而是使用现成的解决方案.

  • @SeanEvans:小心!`import`是一个CL功能,你不需要*!你需要的是*install*包使用,例如,*quicklisp*:`(ql:quickload"split-sequence")` (2认同)

hsr*_*srv 10

对于 Common-Lisp 中的该任务,我发现很有用,(uiop:split-string str :separator " ")并且该包uiop通常有很多实用程序,请查看文档https://common-lisp.net/project/asdf/uiop.html#index-split_002dstring


Ehv*_*nce 5

cl-ppcre:split

* (split "\\s+" "foo   bar baz
frob")
("foo" "bar" "baz" "frob")

* (split "\\s*" "foo bar   baz")
("f" "o" "o" "b" "a" "r" "b" "a" "z")

* (split "(\\s+)" "foo bar   baz")
("foo" "bar" "baz")

* (split "(\\s+)" "foo bar   baz" :with-registers-p t)
("foo" " " "bar" "   " "baz")

* (split "(\\s)(\\s*)" "foo bar   baz" :with-registers-p t)
("foo" " " "" "bar" " " "  " "baz")

* (split "(,)|(;)" "foo,bar;baz" :with-registers-p t)
("foo" "," NIL "bar" NIL ";" "baz")

* (split "(,)|(;)" "foo,bar;baz" :with-registers-p t :omit-unmatched-p t)
("foo" "," "bar" ";" "baz")

* (split ":" "a:b:c:d:e:f:g::")
("a" "b" "c" "d" "e" "f" "g")

* (split ":" "a:b:c:d:e:f:g::" :limit 1)
("a:b:c:d:e:f:g::")

* (split ":" "a:b:c:d:e:f:g::" :limit 2)
("a" "b:c:d:e:f:g::")

* (split ":" "a:b:c:d:e:f:g::" :limit 3)
("a" "b" "c:d:e:f:g::")

* (split ":" "a:b:c:d:e:f:g::" :limit 1000)
("a" "b" "c" "d" "e" "f" "g" "" "")
Run Code Online (Sandbox Code Playgroud)

http://weitz.de/cl-ppcre/#split

对于常见情况,有(新的,“现代且一致的”)cl-str字符串操作库:

(str:words "a sentence    with   spaces") ; cut with spaces, returns words
(str:replace-all "," "sentence") ; to easily replace characters, and not treat them as regexps (cl-ppcr treats them as regexps)
Run Code Online (Sandbox Code Playgroud)

你有cl-slug来删除非 ascii 字符和标点符号:

 (asciify "Eu André!") ; => "Eu Andre!"
Run Code Online (Sandbox Code Playgroud)

以及str:remove-punctuation(使用cl-change-case:no-case)。