开发者

str_replace in Common Lisp?

Is there some function similar to PHP's str_replace in Common Lisp?

http://php开发者_StackOverflow中文版.net/manual/en/function.str-replace.php


There is a library called cl-ppcre:

(cl-ppcre:regex-replace-all "qwer" "something to qwer" "replace")
; "something to replace"

Install it via quicklisp.


I think there is no such function in the standard. If you do not want to use a regular expression (cl-ppcre), you could use this:

(defun string-replace (search replace string &optional count)
  (loop for start = (search search (or result string)
                            :start2 (if start (1+ start) 0))
        while (and start
                   (or (null count) (> count 0)))
        for result = (concatenate 'string
                                  (subseq (or result string) 0 start)
                                  replace
                                  (subseq (or result string)
                                          (+ start (length search))))
        do (when count (decf count))
        finally (return-from string-replace (or result string))))

EDIT: Shin Aoyama pointed out that this does not work for replacing, e.g., "\"" with "\\\"" in "str\"ing". Since I now regard the above as rather cumbersome I should propose the implementation given in the Common Lisp Cookbook, which is much better:

(defun replace-all (string part replacement &key (test #'char=))
  "Returns a new string in which all the occurences of the part 
is replaced with replacement."
  (with-output-to-string (out)
    (loop with part-length = (length part)
          for old-pos = 0 then (+ pos part-length)
          for pos = (search part string
                            :start2 old-pos
                            :test test)
          do (write-string string out
                           :start old-pos
                           :end (or pos (length string)))
          when pos do (write-string replacement out)
          while pos)))

I especially like the use of with-output-to-string, which generally performs better than concatenate.


If the replacement is only one character, which is often the case, you can use substitute:

(substitute #\+ #\Space "a simple example") => "a+simple+example"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜