Count number of times a letter is in a word

自闭症网瘾萝莉.ら 提交于 2019-12-24 09:59:58

问题


I have the word describe, and I want to see how many times each letter appears in the word. Eg "e" appears twice, "d" appears once etc

I have tried

    (for [letter (map str (seq describe))] 
      (count (re-seq letter describe)))

But I get the error

ClassCastException java.lang.String cannot be cast to java.util.regex.Pattern  clojure.core/re-matcher (core.clj:4667)

Any help would be much appreciated


回答1:


You can use frequencies to count the frequency at which each character appears in the string, returning a map like this:

(frequencies "ababacdefg")
=> {\a 3, \b 2, \c 1, \d 1, \e 1, \f 1, \g 1}

This works because the string is being treated as a sequence of characters. frequencies can be used on general collections:

(frequencies [1 1 2 3])
=> {1 2, 2 1, 3 1}

The key is the value being counted, and the value is the frequency.



来源:https://stackoverflow.com/questions/48567380/count-number-of-times-a-letter-is-in-a-word

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!