I'm looking for an equivalent of replace-regexp-in-string
that just uses literal strings, no regular expressions.
(replace-regexp-in-string "." "bar" "foo.buzz") => "barbarbarbarbarbarbarbar"
But I want
(replace-in-string "." "bar" "foo.buzz") => "foobarbuzz"
I tried various replace-*
functions but can't figure it out.
Edit
In return for the elaborate answers I decided to benchmark them (yea, I know all benchmarks are wrong, but it's still interesting).
The output of benchmark-run
is (time, # garbage collections, GC time)
:
(benchmark-run 10000 (replace-regexp-in-string "." "bar" "foo.buzz")) => (0.5530160000000001 7 0.4121459999999999) (benchmark-run 10000 (haxe-replace-string "." "bar" "foo.buzz")) => (5.301392 68 3.851943000000009) (benchmark-run 10000 (replace-string-in-string "." "bar" "foo.buzz")) => (1.429293 5 0.29774799999999857)
replace-regexp-in-string with a quoted regexp wins. Temporary buffers do remarkably well.
Edit 2
Now with compilation! Had to do 10x more iteration:
(benchmark-run 100000 (haxe-replace-string "." "bar" "foo.buzz")) => (0.8736970000000001 14 0.47306700000000035) (benchmark-run 100000 (replace-in-string "." "bar" "foo.buzz")) => (1.25983 29 0.9721819999999983) (benchmark-run 100000 (replace-string-in-string "." "bar" "foo.buzz")) => (11.877136 86 3.1208540000000013)
haxe-replace-string is looking good
Definition and Usage. The str_replace() function replaces some characters with some other characters in a string. This function works by the following rules: If the string to be searched is an array, it returns an array.
The Java string replace() method will replace a character or substring with another character or string. The syntax for the replace() method is string_name. replace(old_string, new_string) with old_string being the substring you'd like to replace and new_string being the substring that will take its place.
Simple Search and Replace Operations When you want to replace every instance of a given string, you can use a simple command that tells Emacs to do just that. Type ESC x replace-string RETURN, then type the search string and press RETURN.
Try this:
(defun replace-in-string (what with in) (replace-regexp-in-string (regexp-quote what) with in nil 'literal))
s.el
string manipulation library has s-replace
function:
(s-replace "." "bar" "foo.buzz") ;; => "foobarbuzz"
I recommend installing s.el
from Emacs package manager, if you work with strings in your Elisp.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With