麻烦计算字符串Common Lisp的子句

时间:2016-01-28 12:13:06

标签: lisp common-lisp

我正在尝试使用函数计数来告诉我“< script>”出现了多少次标签有,但我似乎无法让它工作。我的代码:

(count "<script>" "<p>Hello World</p><script>javascript goes here</script>" :key #'string :test #'equal)

我似乎无法找到它的很多例子,但我找到了一个用于删除,我认为它们是相似的。我怎样才能让它返回1而不是0?

2 个答案:

答案 0 :(得分:4)

Count只计算匹配的单个元素(因此您可以使用它来计算#\ a个字符,例如,但不是子字符串)。为了计算子串,你会想要这样的东西:

(defun count-substrings (substring string)
  (loop
    with sub-length = (length substring)
    for i from 0 to (- (length string) sub-length)
    when (string= string substring
                  :start1 i :end1 (+ i sub-length))
    count it))

当然,像这样计算html标签非常容易出错。您可能想要使用实际的解析器。

答案 1 :(得分:3)

使用原始函数search的简明解决方案:

(defun count-substring(substring string)
  (do ((count -1 (+ count 1))
       (position -1 (search substring string :start2 (1+ position))))
      ((null position) count)))

被修改 在第一个版本中,计数从0开始,但这是不正确的。

相关问题