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: Kaushal Modi
Subject: Re: How to count the number of occurrences of a character in a string?
Date: Mon, 12 Oct 2015 21:43:28 +0000

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))))))

Below is the same code as above with some debug statements:

(let ((char ?a)
      (str "abcda"))
  (message "%0d occurrences of `%c' char found in \"%s\""
           (catch 'break
             (let* ((str str)
                    (len (length str))
                    (num-matches 0)
                    match-pos)
               (dotimes (i len)
                 (message "i = %0d str = %0s" i str)
                 (setq match-pos (string-match-p (char-to-string char) str))
                 (when match-pos
                   (message "match-pos = %0d str = %0s" match-pos str)
                   (setq str (substring-no-properties str (1+ match-pos)))
                   (message "new str = %0s" str)
                   (setq len (length str))
                   (setq num-matches (1+ num-matches)))
                 (when (= 0 len)
                   (throw 'break num-matches)))))
           char str))





On Mon, Oct 12, 2015 at 3:45 PM Marcin Borkowski <mbork@mbork.pl> wrote:

> Hi all,
>
> the subject line says it all.  Is there any built-in Elisp function to
> do that?  Should I just use cl-count?
>
> Best,
>
> --
> Marcin Borkowski
> http://octd.wmi.amu.edu.pl/en/Marcin_Borkowski
> Faculty of Mathematics and Computer Science
> Adam Mickiewicz University
>
>


reply via email to

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