Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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:</p> <pre><code>(defun string-replace (search replace string &amp;optional count) (loop for start = (search search (or result string) :start2 (if start (1+ start) 0)) while (and start (or (null count) (&gt; 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)))) </code></pre> <p><em>EDIT:</em> Shin Aoyama pointed out that this does not work for replacing, e.g., <code>"\""</code> with <code>"\\\""</code> in <code>"str\"ing"</code>. Since I now regard the above as rather cumbersome I should propose the implementation given in the <a href="http://cl-cookbook.sourceforge.net/strings.html#manip" rel="nofollow">Common Lisp Cookbook</a>, which is much better:</p> <pre><code>(defun replace-all (string part replacement &amp;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))) </code></pre> <p>I especially like the use of <code>with-output-to-string</code>, which generally performs better than <code>concatenate</code>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload