Reputation: 89
I am trying to see if a string is over 10,000 characters. if it is, it should print too long
. I know I can do this with strlen
, but then the time complexity is O(n)
, which, isn't too bad, but I still have to iterate through 10,000 characters every time if someone enters 10,000 characters, but if my someone enters 1 million characters, thats a bad n
. So My solution is, to check if the 10,001th character is set. If it is set, then its obviously too long. Would this work? Or would this sometimes work (and depends on how memory was/is being allocated).
Upvotes: 1
Views: 351
Reputation: 55
<?php
if (isset($str[100001])) {
... do my stuff ...
} ?>
The isset function is run on $str[10001] which is only one address in the array, hence o[1]. Also, while accessing key out of index in php, it does not throw error or cause memory leak. It throws an OutOfBoundsException exception which can be caught with a try catch block.
Upvotes: 0
Reputation: 27011
I know I can do this with strlen, but then the time complexity is O(n)
I don't know who tell you this, strlen
is simply returns the len
property.
Definition of strlen, it use ZSTR_LEN
macro to get the string length
ZEND_FUNCTION(strlen)
{
zend_string *s;
ZEND_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_STR(s)
ZEND_PARSE_PARAMETERS_END();
RETVAL_LONG(ZSTR_LEN(s));
}
And the definition of ZSTR_LEN
#define ZSTR_LEN(zstr) (zstr)->len
Upvotes: 2
Reputation: 1337
strlen
already has a time complexity of O(1), due to the fact that length is simply stored as an attribute.
http://php.net/manual/en/function.strlen.php
Upvotes: 1