当前位置:网站首页>统计字符串中每个字符出现的次数
统计字符串中每个字符出现的次数
2022-04-23 05:53:00 【KK要继续努力】
统计字符串中每个字符出现的次数
题目:
统计一个字符串中每个字符出现的次数,并返回出现次数最多的字母以及相应次数
解答:
利用reduce函数,将每个字符看成一个空箱子,遍历到就把值传到空箱子中,最后判断出空箱子里有多少
var str="helloworld";
var arr=str.split("");
var result=arr.reduce(
function(prev,elem){
//到这个数时为这个数添加1次
if(prev[elem]===undefined){
prev[elem]=1;
}else{
prev[elem]+=1;
}
return prev;
},
{
}
)
var char,count;
//遍历result中每个成员
for(var key in result){
//第一遍如果没有
if(char===undefined){
char=key;
count=result[key];
}else{
//否则,开始作比较
if(result[key]>count){
char=key;
count=result[key];
}
}
}
console.log(`${
char}出现次数最多,共出现${
count}次`);
function strNum(str){
let obj = {
};
for(let i=0;i<str.length;i++){
let value = str.charAt(i)
if(obj[value]){
obj[value]++
}else{
obj[value] = 1
}
}
let word = null
let temp = 0
for(let key in obj){
if(obj[key]>temp){
temp = obj[key]
word = key
}
}
return [word, temp].join(' ')
}
console.log(strNum('helloword'));
return返回多个值
- return {a,b,c}
- return [a,b,c]
知识点:reduce()、循环
版权声明
本文为[KK要继续努力]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_45393020/article/details/117984241
边栏推荐
- SDOI2009-HH的项链
- 深蓝学院激光slam 理论与实践 第三章激光雷达去畸变 作业习题
- 深蓝学院激光slam理论与实践 -第二章(里程计标定)作业
- C语言代码规范
- CUDA project encountered a series of compilation problems after changing the environment (computer)
- [UDS unified diagnostic service] II. Network layer protocol (1) - overview and functions of network layer
- Informatics one book pass - small ball
- VHDL 有限状态机(FSM) 代码示例
- 类和对象
- C语言实现memcpy、memset、strcpy、strncpy、strcmp、strncmp、strlen
猜你喜欢

Collection of practical tips for C language (continuously updated)

File viewing commands and user management commands

信息学一本通-小球

QT add qserialport class to realize serial port operation

cv_bridge 与opencv 版本不匹配的解决
![[UDS unified diagnostic service] III. application layer protocol (1)](/img/e7/813e29a30e08eb92ccc836743be9aa.png)
[UDS unified diagnostic service] III. application layer protocol (1)

【UDS统一诊断服务】一、诊断概述(1)— 诊断概述

进程管理命令

VHDL finite state machine (FSM) code example

Introduction to nonparametric camera distortion model
随机推荐
SSH 公钥 私钥的理解
Makefile基础、常用函数及通用Makefile
TP download folder, compress folder and download
汇编 32位无符号加法计算器
PHP junior programmers, take orders and earn extra money
CUDA project encountered a series of compilation problems after changing the environment (computer)
2020 Jiangsu Collegiate Programming Contest-A.Array
【UDS统一诊断服务】一、诊断概述(1)— 诊断概述
SDOI2009-HH的项链
时间戳转格式化日期
Set up a personal blog of jpress
[UDS unified diagnostic service] III. application layer protocol (1)
汇编基础代码示例
[UDS unified diagnostic service] i. overview of diagnosis (4) - basic concepts and terms
客户端软件增量更新
MOS管特性和导通过程
Shell脚本 单引号、双引号和反引号的区别
VHDL arbitrary frequency divider (50% duty cycle)
Eigen 库常用基本用法 备忘
Introduction and application of WMI Technology