Search code examples
clojurepattern-matchingcharacterstring-matchingclojure-repl

(Clojure) Count how many times any character appear in a string


I am trying to write a function (char-count) which takes a pattern and a string, then returns a number (count) which represents how many times any of the characters in the pattern appear in the string.

For example:

(char-count "Bb" "Best buy")

would return 2 since there is 1 match for B and 1 match for b, so added together we get 2

(char-count "AaR" "A Tale of Recursion")

would return 3 and so on


I tried using re-seq in my function, but it seems to work only for continuous strings. As in (re-seq #Bb "Best Buy) only looks for the pattern Bb, not for each individual character.

This is what my function looks like so far:

(defn char-count [pattern text]
  (count (re-seq (#(pattern)) text)))

But it does not do what I want. Can anybody help?

P.s. Very new to clojure (and functional programming in general).


Solution

  • Try wrapping the characters in [...] within the RegEx:

    (count (re-seq #"[Bb]" "Best buy"))
    

    Or, since you need that pattern to be dynamic:

    (count (re-seq (re-pattern (str "[" pattern "]")) text))
    

    But note that the solution might not work properly if the pattern contains special RegEx characters such as [, ], \, -, ^ - you'd have to escape them by prepending \\ in front of each one.