统计字符串

统计字符串

  • 统计一个字符串中字符出现的次数
  • 获得次数最多的一个,共出现几次
  • 用字典的方式
var string = 'hello world';
function statistics(string) {
    
    
	// 定义空字典
	var dictionaries = {
    
    };
	for (var i = 0; i < string.length; i++) {
    
    
		// 如果 dictionaries 
		// 对象不包含当前字母为属性名的成员
		if (dictionaries[string[i]] === undefined) {
    
    
			// 强行添加一个以当前字母为属性名的成员,
			// 初始值为 1
			dictionaries[string[i]] = 1;
		} else {
    
    
			// 如果字典中有这个字母为属性名的成员,
			// 就为当前属性名的值 += 1
			dictionaries[string[i]] += 1;
		};
	};
	return dictionaries;
};
// 字典结构
// { h: 1, e: 1, l: 3, o: 2, w: 1, r: 1, d: 1 }
console.log(statistics(string));

// 利用奥运会跳水比赛记分牌的方式
var max, count = 0;
// 遍历字典中每个属性
for (var key in statistics(string)) {
    
    
	// 用当前属性值和 count 比较
	// 如果当前属性值大于 count 时,
	// 才取而代之,并将当前字符,保存在 max 中
	if (statistics(string)[key] > count) {
    
    
		max = key;
		count = statistics(string)[key];
	};
};
console.log(max, count); // l 3

猜你喜欢

转载自blog.csdn.net/weixin_51157081/article/details/115220048