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

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

Re: count char in string [The Emacs Challenge Competition - round 2, wit


From: Leo Butler
Subject: Re: count char in string [The Emacs Challenge Competition - round 2, with fallout]
Date: Thu, 29 Oct 2020 12:52:14 -0500
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/26.3 (gnu/linux)

Patrick McAllister <pma@rdorte.org> writes:

> ********************************************************
> Caution: This message was sent from outside the University of Manitoba.
> ********************************************************
>
> On Wed, Oct 28 2020, Emanuel Berg via Users list for the GNU Emacs text 
> editor wrote:
>
>> round 2:
>>
>> Very simple: we are looking for a function that returns the number of
>> occurrences of a char in a string.
>>
>> Emanuel Berg's solution:
>>
>> (require 'cl-lib)
>> (defun count-char-in-string (the-char str)
>>   (let ((c  (if (characterp the-char) the-char (string-to-char the-char)))
>>         (cs (string-to-list str)) )
>>     (cl-count c cs) ))
>> ;; (count-char-in-string ?a "Emacs skills kills") ; 1

Here is a solution for interactive use that is far more flexible than
just counting characters.

I use the following a lot when editing documents with a maximum
character count:

M-< M-x replace-regexp [^[:space:]] \& RET

Or, since I bind replace-regexp to C-x a r,

M-< C-x a r [^[:space:]] \& RET

I just did that and the mini-buffer informed me there were 1232
non-space characters in the buffer. 

Leo



reply via email to

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