【问题标题】:LISP - Modify StringLISP - 修改字符串
【发布时间】:2013-04-02 13:16:56
【问题描述】:

我必须编写一个程序,将字符串的元音、辅音和其他符号分别更改为 C、V 0。我已经这样做了,但我想知道是否有更有效和更优雅的方法来做到这一点。不胜感激。

(defun string-to-list (string)
(loop for char across string collect char))

(defun is-vowel (char) (find char "aeiou" :test #'char-equal))

(defun is-consonant (char) (find char "bcdfghjklmnpqrstvwxyz" :test #'char-equal))

(defun letter-type (char)
(if (is-vowel char) "V"
(if (is-consonant char) "C"
"0")))

(defun analyze-word (word-string)
(loop for char across word-string collect (letter-type char)))

另外,我想把它变成一个字符串,我该怎么做呢?我应该定义一个函数来遍历列表并使其成为字符串还是更简单的方法?

【问题讨论】:

标签: string lisp common-lisp


【解决方案1】:
(defun letter-type (char)
  (cond ((find char "aeiou" :test #'char-equal) #\V)
        ((alpha-char-p char) #\C)
        (t #\0)))

CL-USER> (map 'string #'letter-type "analyze-word")
"VCVCCCV0CVCC"

【讨论】:

  • 虽然当我输入“spectacuular22ace”时,它给了我“VCVCCCV0CVCC”,并且壮观的以 v 开头,它是辅音而不是元音,不仅如此,它只打印一个 0 而不是两个 0。
  • 您必须将上面示例中的“analyze-word”替换为您的输入。
【解决方案2】:

只是为了这个想法:

(defun multi-replace-if (sequence function &rest more-functions)
  (map (type-of sequence)
       (lambda (x)
         (loop for f in (cons function more-functions)
            for result = (funcall f x)
            while (eql x result)
            finally (return result)))
       sequence))

(multi-replace-if "bcdfghjklmnpqrstvwxyz"
                  (lambda (x) (if (find x "aeiouy") #\v x))
                  (lambda (y) (declare (ignore y)) #\c))
"cccccccccccccccccccvc"

【讨论】:

    猜你喜欢
    • 2017-09-26
    • 2014-05-30
    • 2018-04-10
    • 2021-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-02
    • 2021-10-04
    相关资源
    最近更新 更多