C Programming/string.h/strlen

From Wikibooks, open books for an open world
Jump to navigation Jump to search

In the C standard library, strlen is a string function that determines the length of a C character string.

Example usage[edit]

#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.


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 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.[2]

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.


  1. "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. 
  2. "Contents of /stable/10/lib/libc/string/strlen.c". FreeBSD. 2013-10-10. http://svnweb.freebsd.org/base/stable/10/lib/libc/string/strlen.c?view=markup. 

External links[edit]