首页 > 解决方案 > 按分隔符拆分字符串并包含分隔符 - 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)))

但这不会打印出最后一个子字符串/单词。我不确定发生了什么事。

提前感谢您的帮助!

标签: stringsplitcommon-lisp

解决方案


如果您只是在寻找解决方案,而不是为了锻炼,您可以使用cl-ppcre

CL-USER> (cl-ppcre:split "(\\.)" "a.bc.def.com" :with-registers-p t)
("a" "." "bc" "." "def" "." "com")

推荐阅读