gpt4 book ai didi

string - 按分隔符拆分字符串并包含分隔符 - Common Lisp

转载 作者:行者123 更新时间:2023-12-03 18:25:08 24 4
gpt4 key购买 nike

如何在 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/

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