Go to the first, previous, next, last section, table of contents.


String Length

You can get the length of a string using the strlen function. This function is declared in the header file `string.h'.

Function: size_t strlen (const char *s)
The strlen function returns the length of the null-terminated string s. (In other words, it returns the offset of the terminating null character within the array.)

For example,

strlen ("hello, world")
    => 12

When applied to a character array, the strlen function returns the length of the string stored there, not its allocated size. You can get the allocated size of the character array that holds a string using the sizeof operator:

char string[32] = "hello, world";
sizeof (string)
    => 32
strlen (string)
    => 12

But beware, this will not work unless string is the character array itself, not a pointer to it. For example:

char string[32] = "hello, world";
char *ptr = string;
sizeof (string)
    => 32
sizeof (ptr)
    => 4  /* (on a machine with 4 byte pointers) */

This is an easy mistake to make when you are working with functions that take string arguments; those arguments are always pointers, not arrays.

Function: size_t strnlen (const char *s, size_t maxlen)
The strnlen function returns the length of the null-terminated string s is this length is smaller than maxlen. Otherwise it returns maxlen. Therefore this function is equivalent to (strlen (s) < n ? strlen (s) : maxlen) but it is more efficient.

char string[32] = "hello, world";
strnlen (string, 32)
    => 12
strnlen (string, 5)
    => 5

This function is a GNU extension.


Go to the first, previous, next, last section, table of contents.