PHP counts the number of occurrences of all characters in a string

Source: Internet
Author: User
PHP counts the number of occurrences of all characters in a string

Effect



Algorithm:

Loop the string once ($str in this example) and record the occurrence of the string in an array (as in this example, $strrecord), if already has this record function is not recorded;

In each string, it is compared to the value of the record array ($strrecord[][' key ' in this case), and if a value in the record is the same as the string, the number of records is +1 ($strrecord[][' count ' of this example);

Of course, set a variable, the default is false (such as the $found of this example), the record each time the comparison, if the record array already has this value, set to True, through this token, the array is not encountered in the array

Code:

<textarea readonly="" name="code" class="php"><?php//The characters appearing in the statistics string, the number of occurrences of echo ' <pre class= ' brush:php;toolbar:false ' > '; $str = ' AAABBCCQQWWEEDFGHHJFFFFFFFFGGGGGGGGG ';//String example echo $str. ' <br/> '; $strRecord =array ();//To record the occurrences of the character in this array, if there is a record, Then do not log, for ($i =0; $i <strlen ($STR); $i + +) {$found = 0;//default setting is not encountered with foreach ((array) $strRecord as $k + = $v) {if ($str [$i] = = $v [' key ']) {$strRecord [$k] [' count '] + = 1;//has been encountered, Count + 1; $found = 1;//settings have been encountered, tag continue;//if you have encountered, do not loop the array of records, Continue to the next string comparison}}if (! $found) {$strRecord [] = Array (' key ' = = $str [$i], ' count ' =>1);//Record not encountered string}}print_r ($strRecord );? ></textarea>


  • Related Article

    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.