日期:2014-05-16 浏览次数:20436 次
Javascript对字符串处理时对象的运用
======================================
使用对象处理字符串:计算频率最多的字符和次数
?<script>??
??? var str = "adadfdfseffserfefsefseeffffftsdg"; //命名一个变量放置给出的字符串??
??? var result = {};??
??? for ( var i = 0; i < str.length; i++) {??
??????? var c = str.charAt(i);??
??????? if (result[c]) {??
??????????? result[c]++;??
??????? } else {??
??????????? result[c] = 1;??
??????? }??
??? }??
??? console.log(result);??
??? var max=0;??
??? var maxChar='';??
??? for ( var key in result) {??
??????? if(result[key]>max){??
??????????? max=result[key];??
??????????? maxChar=key;??
??????? }??
??? }??
??? console.log(maxChar);??
??? console.log(max);??
</script>
小改进后的代码:
var str = "adadfdfseffserfefsefseeffffftsdg"; //命名一个变量放置给出的字符串??
var result = {};??
var max = 0;??
var maxChar = '';??
for ( var i = 0; i < str.length; i++) {??
??? var c = str.charAt(i);??
??? if (result[c]) {??
??????? result[c]++;??
??????????????? if(result[c] > max){??
??????????????????? max = result[c];??
??????????????????? maxChar = c;??
??????????????? }??
??? } else {??
??????? result[c] = 1;??
??? }??
}??
alert(max + ':' +maxChar)?
正则表达式处理字符串:
var a = {};
var maxValue = 0;
var str = "adadseffouyangpingfsffffftsdg";
str.replace(/./g, function(c){
???? var count = a[c] ? (a[c] +1): 1;
???? a[c] = count;
???? maxValue = maxValue < a[c]? a[c] : maxValue;
???? return '';
});
for(var p in a){
?? if(a[p] == maxValue){
???? alert(p + '\t' + maxValue);
???? break;
?? }
}
===================================
使用数组处理字符串:计算频率最多的字符和次数
var maxchar = function(s){??
??? var h = {},t = [0,''];??
??? for(var i = 0 , l = s.length; i < l ; i++){??
??????? if(h[s[i]]){??
??????????? h[s[i]] += 1;??
??????????? if(h[s[i]] > t[0]){??
??????????????? t[0] = h[s[i]];??
??????????????? t[1] = s[i];??
??????????? }??
??????? }else{??
??????????? h[s[i]] = 1;??
??????? }??
??? }??
??? return t;??
}??
console.log(maxchar('adadfdfsedfsdfffserfefsefseeffffftsdg'));
====================================
对所有字符(包括中文字符)都适用:
<script>
var a = "";
var maxValue = 0;
var str = "adadseffouyangpingfsffffftsdg";
while(str.length>0){
??? l = str.length;
??? s = str.charAt(0);
??? str = str.replace(eval("/"+s+"/g"),"");
??? if(maxValue<(l-str.length)){
??????? a = s;
??????? maxValue=l-str.length;
??? }
}
alert(a + maxValue);
</script>