Calculates the most repeated characters and occurrences of a string

Source: Internet
Author: User

Method One:

<script type= "Text/javascript" >var str = ' caibaojian.com ', obj=[];for (var i = 0; i< str.length; i++) {var key = str [I];if (!obj[key]) {Obj[key] = 1;} Else{obj[key] + +;}} var max = -1;var Max_key = "; var key;for (key in obj) {if (Max<obj[key]) {max=obj[key];max_key = key;}} Console.log (max_key+ "is a maximum number of characters and occurs" +max);</script>

Method Two:

var str = "caibaojian.com"; var arr = Str.split (""); var obj = {};var Objarr = [];for (var i=0,j; J=arr[i]; i++) {if (!obj[j]) obj[j]=0;objarr[++obj[j]]=j;} document.write (objarr[objarr.length-1]+ "= =" + (objarr.length-1));

Method Three:

var str = "caibaojian.com"; var maxLength = 0; Name a variable to place the highest number of occurrences of the letter and initialize it to 0var result = '; Name a variable to place the result input while (str! = ") {//loop iteration begins and determine if the string is empty oldstr = str;//Assign the original string variable to the new variable getstr = STR.SUBSTR (0,1);//Subs with string The TR method gets the first character (first letter) of eval ("str = str.replace (/" +getstr+ "/g,") "); Details such as supplement can also be written as str = str.replace (new RegExp (Getstr, ' G '), ""); if (Oldstr.length-str.length > MaxLength) {// Determines the length of the original string minus the substitution after the string length is greater than the maximum string length that appears before maxlength = Oldstr.length-str.length; Subtract two string lengths to get the maximum string length result = getstr + "=" + maxLength//returns the maximum string result (letters, occurrences)}}document.write (Result)//Popup results

Calculates the most repeated characters and occurrences of a string

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.