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

标签 string split common-lisp

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

相关文章:

mysql - 在 SQL 中按年份排序

json - jinja2.exceptions.TemplateRuntimeError : no filter named 'split' 错误

oop - 根据 CLOS(Common Lisp),类型系统的目的是什么?

lisp - 在 Lisp 中编程的正确方法?

java - 获取列表中特定字符串的最后一次出现

python - Python中的字符串格式化

Python tryexcept 用于用 "-"进行分割

python - 将多个值拆分为新行

lisp - 普通口齿不清 : "no non-white-space characters in string"

python - 更高效的 HashMap (Dictionary) for Python 用于大数据