c Programming/C Reference/string.h/strlen

From Wikibooks, open books for an open world
Jump to: navigation, 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.

Implementation[edit]

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.

References[edit]

  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. "strlen.c Revision 1.10". FreeBSD. 2010-03-13. http://www.freebsd.org/cgi/cvsweb.cgi/src/lib/libc/string/strlen.c?rev=1.10. 

External links[edit]