Javascript统计重复字符的的几种方法

日期:2011-09-05    阅读:153   分类:Javascript

//方法1: 使用正则匹配重复的字符,然后根据个数也就是数组长度去排序。
String.count1 = function(str){
    var t = str.split("")
    .sort()
    .join("")
    .replace(/((.)?*)/g,"$1,")
    .split(",")
    .sort(function(a,b){return b.length - a.length});
    return "字符:"+t[0][0]+"次数:"+t[0].length;
}

//方法2: 键-值的思考方法,数组的索引作为“字符”,该索引下的数组值作为“字符个数”
String.count2 = function(str){
    var map={},maxCount=0,maxChar,undefined,i=str.length;
    while(i--){
    var t = str.charAt(i);
    map[t] == undefined ? map[t] = 1 : map[t] += 1;
    if(map[t] > maxCount){
    maxChar = t;
    maxCount = map[maxChar];
    }
    }
    return "字符:"+maxChar+"次数:"+maxCount;
}

//方法3:
String.count3 = function(str){
    var most = str.split('').sort().join('').match(/(.)?*/g); //排列重复字符
    most = most.sort(function(a,b){return a.length - b.length}).pop();//按出现频繁排序
    return most.length + ': ' + most[0];
}

//方法4: json的思考方法,也是键值映射
String.count4 = function(str) {
    var s = str.split(''), o ={}, a=[];
    for(var i = 0; i < s.length; i++) o[s[i]] ? o[s[i]]++ : o[s[i]]=1; //记录数目
    for(var key in o) a[o[key]] ? a[o[key]].push(key) : a[o[key]] = [key]; //取出
    return a.length - 1 + ': ' + a.pop();
}

//方法5:

String.count5 = function (str){
    var most = [], num = 0;
    while( str != '' ){
    var ori = str,
    target = str.substr(0,1), //目标字符
    re = target;
    if(/[$()*+.?]/.test(target)) re = '' + re;
    str = str.replace(new RegExp(re, 'g'), '');
    diff = ori.length - str.length; //计算目标字符数目
    if(diff > num) {
    num = diff;
    most = [target];
    } else if (diff == num) {
    most.push(target);
    }
    }
    return num + ': ' + most;
}

//方法6:
String.count6 = function (str) {
    var o ={}, most=0, most_c=[], i=-1, len=str.length, c=str.split("");
    i=-1; while (++i < len){
    var n = o[c[i]] = (o[c[i]] | 0) + 1;
    if (n > most){ most_c = [c[i]]; most = o[c[i]]; }
    else if (n == most) {most_c.push(c[i])}
    }
    return most + ': ' + most_c;
}

本页链接: http://www.scriptlover.com/static/867-javascript-字符

标签:

相关文章

网友评论

Leave a comment

 required

 required (Not published)

 required