Calculate the Length strlen
suggest change#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 argument is %zu.\n", len);
return EXIT_SUCCESS;
}
This program computes the length of its first command-line argument (argv[1]) and stores the result in len. It then prints that length. For example, when run as program_name "Hello, world!", it outputs The length of the argument is 13. because Hello, world! is 13 bytes long. argv[0] is the program name, so the check is argc != 2.
strlen counts bytes from the beginning of the string up to, but not including, the terminating null character, '\0'. Use it only when the array is known to be null-terminated.
strlen does not count Unicode scalar values or grapheme clusters. A character can occupy more than one byte, so the byte length is not the same as the number of characters. 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));
}
asciiString has 50 bytes in the array
utf8String has 50 bytes in the array
"Hello world!" is 12 bytes
"Γειά σου Κόσμε!" is 27 bytes
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents