Typical strlen()
traverse from first character till it finds \0
.
This requires you to traverse each and every character.
In algorithm sense, its O(N).
Is there any faster way to do this where input is vaguely defined. Like: length would be less than 50, or length would be around 200 characters.
I thought of lookup blocks and all but didn't get any optimization.
strlen() in C-style strings can be replaced by C++ std::strings. sizeof() in C is as an argument to functions like malloc(), memcpy() or memset() can be replaced by C++ (use new, std::copy(), and std::fill() or constructors).
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.
Strlen is not safe to call! Unless you positively know that the string is null- terminated... Are all the functions you use guaranteed to return a null- terminated string?
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'.
Sure. Keep track of the length while you're writing to the string.
Actually, glibc's implementation of strlen
is an interesting example of the vectorization approach. It is peculiar in that it doesn't use vector instructions, but finds a way to use only ordinary instructions on 32 or 64 bits words from the buffer.
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