I am looking for the shortest, simplest and most elegant way to count the number of capital letters in a given string.
+11
A:
function count_capitals($s) {
return strlen(preg_replace('![^A-Z]+!', '', $s));
}
cletus
2009-10-13 02:48:34
+1
A:
It's not the shortest, but it is arguably the simplest as a regex doesn't have to be executed. Normally I'd say this should be faster as the logic and checks are simple, but PHP always surprises me with how fast and slow some things are when compared to others.
function capital_letters($s) {
$u = 0;
$d = 0;
$n = strlen($s);
for ($x=0; $x<$n; $x++) {
$d = ord($s[$x]);
if ($d > 64 && $d < 91) {
$u++;
}
}
return $u;
}
echo 'caps: ' . capital_letters('HelLo2') . "\n";
mimetnet
2009-10-13 03:17:51