Strlen

From Wikipedia, the free encyclopedia

The correct title of this article is strlen. The initial letter is shown capitalized due to technical restrictions.

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

Contents

[edit] Example usage

#include <stdio.h>
#include <string.h>

int main(void)
{
    char *string = "Hello World";
    printf("%d\n", 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 datatype called char. The end of a string is found by searching for the first NULL character in the array.

[edit] Implementation

There are many possible implementations of strlen. The naive functions are generally fast; but other methods do exist. The function is usually read the function from a library.

[edit] Naive

A possible implementation of strlen might be:

int strlen(char *str)
{
   char *s;
   for(s=str; *s; s++);
   return s-str;
}

The above implementation reads the string from beginning to end to search for a NULL character. It stops when it sees a NULL character, and the difference between the pointers of the location of the NULL character and the beginning of the string is returned.

[edit] Assembly

Sometimes the header files for a particular C library emit fast inline versions of strlen written in assembly. The compiler may also do this; or the header files may simply call compiler built-in versions.

Writing strlen in assembly is primarily done for speed. The complexity of code emitted from a compiler is often higher than hand-optimized assembly, even for very short functions. Further, a function call requires setting up a proper call frame on most implementations; these operations can outweigh the size of simple functions like strlen.