Home > Net >  How to count and print characters that occur at least Y times?
How to count and print characters that occur at least Y times?

Time:11-03

I want to count the number of occurrences of each character in a string and print the ones that occur at least Y times.

Example :

Examples func(X: string, Y: int):
func("UserGems",2) => ["s" => 2, "e" => 2]
func("UserGems",3) => []

This what I could achieve so far:

$str = "PHP is pretty fun!!";
    $strArray = count_chars($str, 1);
    $num = 1;
    foreach ($strArray as $key => $value) {
      if ($value = $num) {
          echo "The character <b>'".chr($key)."'</b> was found $value time(s)           
          <br>";
      }
    }

CodePudding user response:

Firstly, you need to list all letters count with separately and to calculate it. Also, you need to calculate elements equal to count which is your find. I wrote 3 types it for your:

<?php

function check($string,$count) {
    $achives = [];
    $strings = [];
    $strArray = count_chars($string, 1);
    if($count) {
        foreach($strArray as $char => $cnt) {
            if($cnt==$count) {
                $achives[chr($char)] = $cnt;
            }
        }
    }   
    return $achives;
}

echo '<pre>';
print_r(check("aa we are all theere Tural a1",1));

So, it is very short version

function check($string,$count = 1) {
    $achives = [];
    $strArray = count_chars($string, 1);
    array_walk($strArray,function($cnt,$letter) use (&$achives,$count){
          $cnt!==$count?:$achives[chr($letter)] = $cnt;
    });
    return $achives;
}

echo '<pre>';
print_r(check("aa we are all theere Tural a1",3));

But it is exactly answer for your question:

<?php

function check($string,$count) {
    $achives = [];
    $strings = [];
    $strArray = str_split($string, 1);

    foreach($strArray as $index => $char ){
        $strings[$char] = isset($strings[$char])?  $strings[$char]:1;
    }
    
    if($count) {
        foreach($strings as $char => $cnt) {
            if($cnt==$count) {
                $achives[$char] = $cnt;
            }
        }
    }   
    return $achives;
    
}
<?php

function check($string,$count) {
    $achives = [];
    $strings = [];
    $strArray = count_chars($string, 1);

    
    
    if($count) {
        foreach($strArray as $char => $cnt) {
            if($cnt==$count) {
                $achives[chr($char)] = $cnt;
            }
        }
    }   
    return $achives;
}

echo '<pre>';

print_r(check("aa we are all theere Tural a1",1));

CodePudding user response:

You can simply do this with php str_split() and array_count_values() built in functions. i.e.

$chars = str_split("Hello, World!");
$letterCountArray = array_count_values($chars);
    
foreach ($letterCountArray as $key => $value) {
    echo "The character <b>'".$key."'</b> was found $value time(s)\n";
}

Output

  •  Tags:  
  • php
  • Related