In the C standard library, strlen is a string function that determines the length of a C character string.
Contents |
Example usage
#include <stdio.h> #include <string.h> int main(void) { char *string = "Hello World"; printf("%lu\n", (unsigned long)strlen(string)); return 0; }
This program will print the value 11, which is the length of the string "Hello World". Character strings are stored in an array of a data type called char. The end of a string is found by searching for the first null character in the array.
Implementation
FreeBSD 6.2 implements strlen like so:[1]
size_t strlen(const char * str) { const char *s; for (s = str; *s; ++s); return(s - str); }
It is possible to write faster versions in C that examines more than one byte at once, such as an entire word of 4 or 8 bytes. Bitwise operations are used to detect if one of the bytes is null. The current FreeBSD implementation does this.[2]
Modern processors often include a machine-language instruction to calculate strlen that is faster than anything a C compiler could produce normally. Good compilers or header files for a particular C library will emit fast inline versions of strlen written in assembly.
Good compilers will often optimize calls to strlen with constant strings arguments, doing the calculation at compile time.
No optimization can make strlen fast for significantly large inputs, so storing the length of strings is generally the recommended fix. It is also possible to merge the length measurement into another O(n) function such as copying the string, strlcpy is an example.
References
- ^ "strlen.c Revision 1.4". FreeBSD. 2002-03-21. http://www.freebsd.org/cgi/cvsweb.cgi/src/lib/libc/string/strlen.c?rev=1.4. Retrieved 2009-03-04.
- ^ "strlen.c Revision 1.6". FreeBSD. 2009-01-25. http://www.freebsd.org/cgi/cvsweb.cgi/src/lib/libc/string/strlen.c?rev=1.6. Retrieved 2009-03-04.
External links
This entry is from Wikipedia, the leading user-contributed encyclopedia. It may not have been reviewed by professional editors (see full disclaimer)




