Function: subst-char-in-string

subst-char-in-string is a byte-compiled function defined in subr.el.gz.

Signature

(subst-char-in-string FROMCHAR TOCHAR STRING &optional INPLACE)

Documentation

Replace FROMCHAR with TOCHAR in STRING each time it occurs.

Unless optional argument INPLACE is non-nil, return a new string.

View in manual

Aliases

semantic-subst-char-in-string (obsolete since 28.1)

Source Code

;; Defined in /usr/src/emacs/lisp/subr.el.gz
;;;; Replacement in strings.

(defun subst-char-in-string (fromchar tochar string &optional inplace)
  "Replace FROMCHAR with TOCHAR in STRING each time it occurs.
Unless optional argument INPLACE is non-nil, return a new string."
  (if (and (not inplace)
           (if (multibyte-string-p string)
               (> (max fromchar tochar) 127)
             (> tochar 255)))
      ;; Avoid quadratic behavior from resizing replacement.
      (let ((res (string-replace (string fromchar) (string tochar) string)))
        (unless (eq res string)
          ;; Mend properties broken by the replacement.
          ;; Not fast, but this case never was.
          (dolist (p (object-intervals string))
            (set-text-properties (nth 0 p) (nth 1 p) (nth 2 p) res)))
        res)
    (let ((i (length string))
	  (newstr (if inplace string (copy-sequence string))))
      (while (> i 0)
        (setq i (1- i))
        (if (eq (aref newstr i) fromchar)
	    (aset newstr i tochar)))
      newstr)))