I have read that use of strlen
is more expensive than such testing like this:
We have a string x
100 characters long.
I think that
for (int i = 0; i < strlen(x); i++)
is more expensive than this code:
for (int i = 0; x[i] != '\0'; i++)
Is it true? Maybe the second code will not work in some situation so is it better to use the first?
Will it be better with the below?
for (char *tempptr = x; *tempptr != '\0'; tempptr++)
The strlen() function calculates the length of a given string. The strlen() function is defined in string. h header file. It doesn't count null character '\0'.
The time complexity of standard strlen is O(n). Since all trailing characters are '\0', we can use binary search. By comparing middle two elements with '\0', we can decide whether we need to recur for left half or right half. IF one of them is \0, then we found the first occurrence.
The strlen() function determines the length of string excluding the ending null character. The strlen() function returns the length of string . This example determines the length of the string that is passed to main() .
strlen() counts the number of characters up to, but not including, the first char with a value of 0 - the nul terminator.
for (int i=0;i<strlen(x);i++)
This code is calling strlen(x)
every iteration. So if x
is length 100, strlen(x)
will be called 100 times. This is very expensive. Also, strlen(x)
is also iterating over x
every time in the same way that your for loop does. This makes it O(n^2) complexity.
for (int i=0;x[i]!='\0';i++)
This code calls no functions, so will be much quicker than the previous example. Since it iterates through the loop only once, it is O(n) complexity.
The first code checks length of x in every iteration of i and it takes O(n) to find the last 0, so it takes O(n^2), the second case is O(n)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With