help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Swapping characters in a word inside elisp code


From: Marcin Borkowski
Subject: Re: Swapping characters in a word inside elisp code
Date: Fri, 28 Jul 2023 22:45:42 +0200
User-agent: mu4e 1.1.0; emacs 30.0.50

On 2023-07-28, at 21:44, uzibalqa <uzibalqa@proton.me> wrote:

> Sent with Proton Mail secure email.
>
> ------- Original Message -------
> On Saturday, July 29th, 2023 at 6:03 AM, uzibalqa <uzibalqa@proton.me> wrote:
>
>
>> I have a word and want to swap characters at position i with position j.
>>
>> What would be a good way to do this ? Would I need to change structure
>> (to array, vector or some other thing) ?
>
> I have done it this way, but it fails when p > q
>
> How can I solve this ?
>
> (defun cswap (wstr p q)
>   "Replace characters in WSTR at positions P and Q."
>
>   (let ( (char1 (elt wstr p))
>          (char2 (elt wstr q)) )
>
>     (if (and char1 char2)
>         (concat (substring wstr 0 p)
>                 (char-to-string char2)
>                 (substring wstr (+ p 1) q)
>                 (char-to-string char1)
>                 (substring wstr (+ q 1)))) ))

I'd probably use `format', not `concat'.  Alternatively, it might be
closer to idiomatic Elisp to put the word in a buffer and perform the
swap using editing operations (though this makes more sense for larger
things like words in a sentence, and probably less so for characters in
a word).

Also, if your code works only for p < q (which I believe you without
checking myself since it's about 22:45 here and my brain doesn't
function very well), why not include a check for q < p at the beginning
and call the same function recursively with p and q swapped?

Hth,

-- 
Marcin Borkowski
http://mbork.pl



reply via email to

[Prev in Thread] Current Thread [Next in Thread]