Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to find first uppercase character in a string

Suppose you have this string:

hiThere

What is the fastest way to find where the first upper case character is? (T in this example)

I am worried about performance as some words are quite long.

like image 535
Martin Avatar asked Apr 13 '12 08:04

Martin


2 Answers

Easiest would be to use preg_match (if there is only 1 match) or preg_match_all (if you want all the matches) http://php.net/manual/en/function.preg-match.php

preg_match_all('/[A-Z]/', $str, $matches, PREG_OFFSET_CAPTURE);

Not sure if it is the fastest..

like image 191
crazyphoton Avatar answered Oct 22 '22 06:10

crazyphoton


Here's a (more or less) one line solution.

$pos = strcspn($string, 'ABCDEFGHJIJKLMNOPQRSTUVWXYZ');

strcspn will return the position of the first occurrence of any character in the second argument, or the length of the string if no character occurs.

Returns the length of the initial segment of str1 which does not contain any of the characters in str2.

$pos = strcspn($string, 'ABCDEFGHJIJKLMNOPQRSTUVWXYZ');
if ($pos < strlen($string)) {
    echo "capital letter as index $pos";
}
like image 36
Tim Avatar answered Oct 22 '22 04:10

Tim