reddit / emacs

Elisp / How to insert a char at a fixed position in a string

konrad1977 · 2022-09-08 16:16
Let say you have (setq myId "00223344556677") and now you want to format it as "002233-44556677" I can't find a good way to insert a character. Thanks
MitchellMarquez42 · 2022-09-08 16:31
I'd use a temp buffer `(with-temp-buffer)`. Insert the value of myId `(goto-char) ` wherever you want to put the hyphen Insert it Get the text from the buffer, for example with `(buffer-substring-no-properties)`
raevnos · 2022-09-08 17:09
(concat (substring myId 0 6) "-" (substring myId 6))
konrad1977 · 2022-09-08 17:19
Thanks, exactly what I was looking for.
c256 · 2022-09-10 04:38
Are you doing this enough to worry about efficiency? If so, you might care that string literals are effectively immutable in elisp (IIRC), and so taking a string apart and adding pieces will create multiple strings in memory. Garbage Collection means that you don’t have to worry about memory management, until you’re doing something often/quickly enough that gc becomes a concern. (The alternative is *probably* to use **and re-use** an emacs buffer, which is expressly designed to hold mutable sequences of characters.)
konrad1977 · 2022-09-10 05:29
One timer, just to fix the correct id to send to the compiler. So no. But thanks for the heads up!