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

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

Re: How to count the number of occurrences of a character in a string?


From: Nick Dokos
Subject: Re: How to count the number of occurrences of a character in a string?
Date: Mon, 12 Oct 2015 19:27:43 -0400
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/25.0.50 (gnu/linux)

Kaushal Modi <kaushal.modi@gmail.com> writes:

> I took it up as an elisp exercise and got the below (not sure if it is
> performance optimal for your application):
>
> The catch form returns the number of matches.
>
> (let ((char ?a)
>       (str "abcda"))
>   (catch 'break
>     (let* ((str str)
>            (len (length str))
>            (num-matches 0)
>            match-pos)
>       (dotimes (i len)
>         (setq match-pos (string-match-p (char-to-string char) str))
>         (when match-pos
>           (setq str (substring-no-properties str (1+ match-pos)))
>           (setq len (length str))
>           (setq num-matches (1+ num-matches)))
>         (when (= 0 len)
>           (throw 'break num-matches))))))
>

What happens if len never becomes 0 in the loop? E.g looking for "f" in
"falala" or "alala"? No throw, so catch returns nil: you probably want
to add another throw outside the loop; or (better) do something else
when match-pos is nil (there are no more matches), so you don't go
through the loop uselessly:

         (if match-pos
           (progn
             (setq str ...)
             (setq len ...)
             (setq nm-matches))
            (throw 'break num-matches))

But I suspect cl-count will be much faster.

Nick





reply via email to

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