C Language Calculate the Length: strlen()


Example

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

int main(int argc, char **argv) 
{
    /* Exit if no second argument is found. */
    if (argc != 2) 
    {
        puts("Argument missing.");
        return EXIT_FAILURE;
    }

    size_t len = strlen(argv[1]);
    printf("The length of the second argument is %zu.\n", len);

    return EXIT_SUCCESS;
}

This program computes the length of its second input argument and stores the result in len. It then prints that length to the terminal. For example, when run with the parameters program_name "Hello, world!", the program will output The length of the second argument is 13. because the string Hello, world! is 13 characters long.

strlen counts all the bytes from the beginning of the string up to, but not including, the terminating NUL character, '\0'. As such, it can only be used when the string is guaranteed to be NUL-terminated.

Also keep in mind that if the string contains any Unicode characters, strlen will not tell you how many characters are in the string (since some characters may be multiple bytes long). In such cases, you need to count the characters (i.e., code units) yourself. Consider the output of the following example:

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

int main(void) 
{
    char asciiString[50] = "Hello world!";
    char utf8String[50] = "Γειά σου Κόσμε!"; /* "Hello World!" in Greek */

    printf("asciiString has %zu bytes in the array\n", sizeof(asciiString));
    printf("utf8String has %zu bytes in the array\n", sizeof(utf8String));
    printf("\"%s\" is %zu bytes\n", asciiString, strlen(asciiString));
    printf("\"%s\" is %zu bytes\n", utf8String, strlen(utf8String));
}

Output:

asciiString has 50 bytes in the array
utf8String has 50 bytes in the array
"Hello world!" is 12 bytes
"Γειά σου Κόσμε!" is 27 bytes