如何在 Common Lisp 中通过分隔符拆分字符串,就像在 SPLIT-SEQUENCE 中所做的那样,但还要在字符串列表中添加分隔符?
例如,我可以写:(split-string-with-delimiter #\. "a.bc.def.com")
结果是 ("a" "." "bc" "." "def" "." "com")
.
我试过下面的代码( make-adjustable-string
制作一个可以用 vector-push-extend
扩展的字符串):
(defun make-adjustable-string (s)
(make-array (length s)
:fill-pointer (length s)
:adjustable t
:initial-contents s
:element-type (array-element-type s)))
(defun split-str (string &key (delimiter #\ ) (keep-delimiters nil))
"Splits a string into a list of strings, with the delimiter still
in the resulting list."
(let ((words nil)
(current-word (make-adjustable-string "")))
(do* ((i 0 (+ i 1))
(x (char string i) (char string i)))
((= (+ i 1) (length string)) nil)
(if (eql delimiter x)
(unless (string= "" current-word)
(push current-word words)
(push (string delimiter) words)
(setf current-word (make-adjustable-string "")))
(vector-push-extend x current-word)))
(nreverse words)))
但这不会打印出最后一个子字符串/单词。我不确定发生了什么。
提前感谢您的帮助!
最佳答案
如果您只是在寻找解决方案,而不是为了练习,您可以使用 cl-ppcre
:
CL-USER> (cl-ppcre:split "(\\.)" "a.bc.def.com" :with-registers-p t)
("a" "." "bc" "." "def" "." "com")
关于string - 按分隔符拆分字符串并包含分隔符 - Common Lisp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59516459/