Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looking for a replace-in-string function in elisp

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

like image 948
spike Avatar asked Jun 26 '13 16:06

spike


People also ask

Which function is used to replace string?

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.

How do I replace text in a string?

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.

How do I replace all in Emacs?

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.


2 Answers

Try this:

(defun replace-in-string (what with in)   (replace-regexp-in-string (regexp-quote what) with in nil 'literal)) 
like image 194
Trey Jackson Avatar answered Oct 05 '22 00:10

Trey Jackson


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.

like image 41
Mirzhan Irkegulov Avatar answered Oct 05 '22 00:10

Mirzhan Irkegulov