Home  >  Article  >  Backend Development  >  How to count the number of occurrences of each character in a string

How to count the number of occurrences of each character in a string

藏色散人
藏色散人Original
2021-03-19 10:54:4421133browse

Method to count the number of occurrences of each character in a string: first create a PHP sample file; then record the characters that have appeared in an array; finally, use a foreach loop to traverse and count the characters that appear in the string Just the number of times.

How to count the number of occurrences of each character in a string

The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer

The example of this article describes the implementation of PHP statistics on all characters in the character How to count the number of occurrences in a string. Share it with everyone for your reference, the details are as follows:

Let’s take a look at the effect first:

How to count the number of occurrences of each character in a string

Algorithm:

Loop the string once ( $str in this example), records the strings that have appeared in an array (such as $strRecord in this example). If this recording function already exists, it will not be recorded;

in each string When, compare it with the value of the record array ($strRecord[]['key'] in this example). If a value in the record is the same as this string, record the number of times 1 ($strRecord[ in this example ]['count']);

Of course, set a variable, the default is false (such as $found in this example), record each comparison, if the record array already has this value, set it to true , through this mark, record the array that has not been encountered into the array

Implementation code:

<?php
//统计字符串中出现的字符,出现次数
echo &#39;<pre class="brush:php;toolbar:false">&#39;;
$str = &#39;aaabbccqqwweedfghhjffffffffggggggggg&#39;;//字符串示例
echo $str.&#39;<br/>&#39;;
$strRecord=array();//把出现过的字符记录在此数组中,如果记录有,则不记录,
for($i=0;$i<strlen($str);$i++){
 $found = 0;//默认设置为没有遇到过
 foreach((array)$strRecord as $k=>$v){
  if($str[$i] == $v[&#39;key&#39;]){
   $strRecord[$k][&#39;count&#39;] += 1;//已经遇到,count + 1;
   $found = 1;//设置已经遇到过的,标记
   continue;//如果已经遇到,不用再循环记录数组了,继续下一个字符串比较
  }
 }
 if(!$found){
  $strRecord[] = array(&#39;key&#39;=>$str[$i],&#39;count&#39;=>1);//记录没有遇到过的字符串
 }
}
print_r($strRecord);
?>

[Recommended: PHP video tutorial]

The above is the detailed content of How to count the number of occurrences of each character in a string. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn