理系学生日記

おまえはいつまで学生気分なのか

句読点の数え上げ

whileを使って、リージョン内の句読点、ピリオド、カンマ、セミコロン、コロン、感嘆符、疑問符を数える関数を書いてみよ。また、再帰を使って書いてみよ。

while 版.非常に手続き型っぽいコードです.

(defun count-specialchars-region (beginning end)
  (interactive "r")
  (save-excursion
    (let ((count 0))
      (goto-char beginning)

      (while (and (< (point) end)
                  (re-search-forward "[.,;:!?]" end t))
        (setq count (1+ count)))

      (cond ((zerop count)
             (message "The region does not have any special characters"))
            ((= 1 count)
             (message "The region has 1 special character"))
            (t
             (message "The region has %d special characters" count))))))

再帰版.

(defun count-specialchars-region (beginning end)
  (interactive "r")
  (save-excursion
    (goto-char beginning)
    (let ((count (recursive-count-specialchar-region end)))
      (cond ((zerop count)
             (message "The region does not have any special characters"))
            ((= 1 count)
             (message "The region has 1 special character"))
            (t
             (message "The region has %d special characters" count))))))

(defun recursive-count-specialchar-region (end)
  (if (and (< (point) end)
           (re-search-forward "[.,;:!?]" end t))
      (1+ (recursive-count-specialchar-region end))
    0))