Get non-repeated characters in string and count them

374 Views Asked by At

I need to process a string like abclkjabc and return only 3 which counts characters l, k, and j.

I've tried this.

$stringArr = [];
foreach(str_split($string) as $pwd) {
   if(!in_array($pwd, $stringArr)) {
      $stringArr[] = $pwd;
   }
}
$uniqChar = count($stringArr);
3

There are 3 best solutions below

0
Gustavo Marmentini On BEST ANSWER

Try the following instead:

function getNonRepeatingCharacters($str) {
    $counter = [];
    $spllitted = str_split($str);
    foreach($spllitted as $s) {
        if(!isset($counter[$s])) $counter[$s] = 0;
        $counter[$s]++;
    }
    $non_repeating = array_keys(array_filter($counter, function($c) {
        return $c == 1;
    }));

    return $non_repeating;
}

$string = "abclkjabc";
$handle = getNonRepeatingCharacters($string);
0
Prince Dorcis On

Try this:

function getNonRepeatingChars($str) {
    $uniqueLetters = '';
    $multipleLetters = '';
    $arrayStr = str_split($str);

    foreach ($arrayStr as $index => $letter) {
        if (strpos($multipleLetters, $value) !== false || strpos($str, $value, $index + 1) !== false) {
            $multipleLetters .= $value;
            continue;
        }

        $uniqueLetters .= $value;
    }

    return $uniqueLetters;
}
echo getNonRepeatingChars('abclkjabc'); // lkj
4
mickmackusa On

Functional programming and no temporary variable declarations:

  1. Create an array of characters
  2. Count the occurrences of each character
  3. Retain only characters that occurred once (array_filter() also works but is more verbose)
  4. Re-join the qualifying characters

Code: (Demo) (or just the count)

echo implode(
         array_keys(
             array_intersect(
                 array_count_values(
                     str_split('abclkjabc'),
                 ),
                 [1]
             )
         )
     );

Or with semi-functional with a loop: (Demo) (or just the count)

$unique = '';
foreach (array_count_values(str_split('abclkjabc')) as $char => $count) {
    if ($count === 1) {
        $unique .= $char;
    }
}
echo $unique;

Output:

lkj

Getting the length of the output string can be done with strlen().


Instead of splitting the string and count array values, you can count character values with count_chars(). (Demo)

$string = 'abclkjabc';
$notRepeated = [];
foreach (count_chars($string, 1) as $char => $count) {
    if ($count === 1) {
        $notRepeated[] = chr($char);
    }
}
var_export($notRepeated);
echo "\nCount = " . count($notRepeated);

Ultimately, if you only need the count of non-repeated characters, this one-liner will get you there. (Demo)

echo count(array_filter(count_chars($string, 1), fn($count) => $count === 1));