CodeBlanks Logo Icon CodeBlanks

strlen

Learn to get the string length with strlen.

String length with strlen

The strlen function from <string.h> returns the number of characters in a string up to the null terminator. The null character is not counted.

#include <string.h>
size_t n = strlen("Hello");  /* n = 5 */

The returned value is of type size_t; when printing with printf, use the %zu format specifier. sizeof returns the full array size, while strlen returns only the letter count; the two are different.

How strlen works

strlen scans the string from the start and counts until it sees '\0'. If you forget to terminate the array, the function runs past it; this is undefined behavior.

char name[] = "Anna";
size_t len = strlen(name);
/* len = 4 */

So either initialize strings with a literal or add '\0' by hand. strlen is short for string length.

Practice Compute the string length

Define a char array with the "Marie" literal. Find the letter count with strlen and print with printf %zu. Output should be 5.

Starter code

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

int main(void) {
    /* define char array with "Marie" */
    /* strlen for length and printf %zu to print */
    return 0;
}

Sample solution

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

int main(void) {
    char s[] = "Marie";
    printf("%zu\n", strlen(s));
    return 0;
}

Expected output

5

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 strlen vs sizeof

Term Meaning
strlen letter count
sizeof byte size
%zu size_t format
string.h strlen header

2 Format for strlen return type

Question
printf("____
", strlen(name));
Answer
printf("%zu
", strlen(name));

Explanation: Answer is %zu. strlen returns size_t; use %zu in printf.

3 What does `strlen("Anna")` return?

main.c
size_t n = strlen("Anna");
  • 5
  • 4 Correct answer
  • 6
  • 7

Explanation: Anna has 4 letters; strlen returns the count without the null.

All lessons in Beginner