411 REFERENCE · Wikibooks
C programming/string.h/strlen
Reference material by Wikibooks contributors. This retains its source identity and is not 411 news reporting.
In the C standard library, strlen is a string function that determines the length of a C character string.
Example usage
#include <stdio.h>
#include <string.h>
int main()
{
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.
Note importantly that this length does *NOT* include the array entry for the trailing null byte required for the ending character of C strings. Thus, if you need to copy the C string, you need to allocate a space of strlen() + 1.
Implementation
FreeBSD 6.2 implements strlen like so: http://www.freebsd.org/cgi/cvsweb.cgi/src/lib/libc/string/strlen.c?rev=1.4
strlen.c Revision 1.4
FreeBSD
2002-03-21 2009-03-04
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 full machine word rather than byte-by-byte. Hacker's Delight has given an algorithm that makes use of bitwise operations to detect if any of these bytes is nul ('\0'). The current FreeBSD implementation does this. http://svnweb.freebsd.org/base/stable/10/lib/libc/string/strlen.c?view=markup
Contents of /stable/10/lib/libc/string/strlen.c
FreeBSD
2013-10-10
Modern C compilers usually provide fast inline versions of strlen written in assembly, either using the bitwise operation technique or a special instruction provided by certain CISC processors. In addition, strlen of a quoted string constant is often optimized into a constant integer.
References
External links
3 strlen calculate the length of a string
C++ reference for std::strlen
deep