Jump to content

check even number of each character in string


c_pattle

Recommended Posts

I was wondering if anyone knows a good way to check for an even number of each character in a string.  For example if the string is "abbacc" then it will return true as there are two of each character.  However if the string is "ababc" it will return false as there is only 1 c.  Thanks for any help

You'd need to split the string using str_split. Then loop over each letter and add it to another array, then remove it from that array again if there is another of the same letter. If there is anything in the array at the end, then there were odd leters. Like this:

 

$string = 'abcabc';

$odds = array();
foreach(str_split($string) as $letter){
if(($pos = array_search($letter, $odds)) !== false){
	array_splice($odds, $pos, 1);
}else{
	$odds[] = $letter;
}
}

if(empty($odds)){
echo "String is even.";
}else{
echo "String is odd.";
}

 

Good luck.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.