string - 按分隔符拆分字符串并包含分隔符 - 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")
推荐阅读
- git - 使用 ssh 查看我的 GitHub 组织中的存储库
- mysql - 使用 Node.js 并在 AWS lambda 中编写的关闭数据库连接(Mysql)的正确方法是什么
- c++ - C++ ADO Excel 记录删除
- google-apps-script - 如何使此函数在具有多个工作表 ID 的循环中运行?
- json - ansible 将 json 解析为 include_tasks 循环
- amazon-ec2 - 从 Azure Devops 部署到 VPN 后面的 AWS 机器
- android - Flutter - 如何在侦听器延迟后检查值?
- python - 根据最大值对列表值进行分组
- powershell - 在没有实用程序的情况下通过 Powershell 在 WMIObject 中设置 SMBIOSAssetTag
- php - Laravel 中的控制器路由给出空值