统计字符串出现的次数

统计每个字符出现的次数?这个怎么写比较简单?
babajpppwwwonjust

阅读 2.4k
3 个回答
//Array.from('babajpppwwwonjust')
'babajpppwwwonjust'.split('').reduce((obj, s) => {
    obj[s] = (obj[s] || 0) + 1
    return obj
}, {})

只会遍历不重复的字符

const charTotal =(str='')=>{
  let res = {};
  do {
    let s = str.substr(0,1);
    let reg = new RegExp(s,'ig');
    let num = str.match(reg).length;
    res[s] = num;
    str = str.replace(reg,'');
  } while (str.length>0);
  return res;
}
let str = 'babajpppwwwonjust';
charTotal(str);

image.png

看了一下相似问题 https://segmentfault.com/q/10...
大佬们也有相同的解决方法。

__author__ = 'Kangjie Lee'
__mtime__  = '2021/09/03 13:28:04'
__email__  = 'Jwjier@gmail.com'
 
# 方法1:统计单个字符出现次数
def str_count_one(strs:str, find_str:str):
    return strs.count(find_str)
 
# 方法2:统计全部字符出现次数
def str_count_three(strs:str):
    from collections import Counter
    return Counter(strs)
 
if __name__ == '__main__':
   aa =  str_count_one('sfbabajpppwwwonjustsfdsf', 's')
   bb =   str_count_three('babajpppwwwonjust')


   print(aa)
   print(bb)
推荐问题
宣传栏