marting 发表于 2025-4-17 16:02:55

XD::STR:to-list


;;; ------------------------------------------------------------------------
;;; 函数名称 / Function Name: XD::STR:to-list
;;;
;;; 【功能说明 / Description】
;;;   将一个字符串按指定分隔符切分成一个字符串列表。
;;;   Splits a string into a list of substrings based on a given delimiter.
;;;
;;; 【参数说明 / Parameters】
;;;   a - 分隔符字符串,例如 ";"。
;;;         Delimiter string, e.g., ";".
;;;   b - 要分割的字符串,例如 "A;B;C"。
;;;         The target string to split, e.g., "A;B;C".
;;;
;;; 【返回值 / Return Value】
;;;   返回一个字符串列表,每个元素是原始字符串中被分隔符拆分的部分。
;;;   Returns a list of substrings split from the original string.
;;;
;;; 【依赖函数 / Dependencies】
;;;   - XD::STR:m-find:查找所有匹配子串的位置,返回一个整数列表。
;;;       XD::STR:m-find: Finds all positions of the delimiter and returns an index list.
;;;
;;; 【使用示例 / Example Usage】
;;;   (XD::STR:to-list ";" "A;B;C")       =>'("A" "B" "C")
;;;   (XD::STR:to-list "," "hello,world") =>'("hello" "world")
;;;
;;; 【备注 / Notes】
;;;   - 支持任意长度的分隔符。
;;;       Supports multi-character delimiters.
;;;   - 如果未找到分隔符,返回的列表只包含原始字符串。
;;;       If no delimiter is found, returns the original string as the sole element.
;;; ------------------------------------------------------------------------

(defun XD::STR:to-list (a b / n c lst lst2 leng)
;; 查找所有分隔符的位置 / Find all delimiter positions
(setq lst (XD::STR:m-find a b))
(setq n 0)

(if lst
    (progn
      ;; 提取第一个分隔符之前的部分 / Part before the first delimiter
      (setq c (substr b 1 (- (nth 0 lst) 1)))
      (setq lst2 (append lst2 (list c)))

      ;; 提取中间每段 / Parts between delimiters
      (repeat (- (length lst) 1)
      (setq leng (- (nth (+ n 1) lst) (nth n lst) (strlen a)))
      (setq c (substr b (+ (nth n lst) (strlen a)) leng))
      (setq lst2 (append lst2 (list c)))
      (setq n (+ 1 n))
      )

      ;; 提取最后一段 / Part after the last delimiter
      (setq c (substr b (+ (nth n lst) (strlen a))))
      (setq lst2 (append lst2 (list c)))
    )
    ;; 如果没有分隔符,直接返回整个字符串 / No delimiter found: return the string as a single-element list
    (progn
      (setq lst2 (append lst2 (list b)))
    )
)
lst2
)

bghyu 发表于 前天 13:59

:'(:loveliness:;P
页: [1]
查看完整版本: XD::STR:to-list