C Workshop · String Length
Lesson C

String Length

Read a word and print how many characters it has (no spaces).

What it is

String length is how many visible characters sit before the terminator. For the word Kodin that number is 5, not 6, and not the 64-byte size of the buffer.

Approach

  1. scanf the word into a buffer.
  2. Call strlen(s).
  3. Print the count with %zu (or %d with a cast).

Where this is used in the real world

Diagram

1

Kodin

input

2

strlen

walk to \0

3

5

output

Run algorithm

Each step highlights the matching C line. Program output appears only when a line that prints actually runs.

Ready
C code
1#include <stdio.h>
2#include <string.h>
3int main(void) {
4    char s[64];
5    scanf("%63s", s);
6    printf("%zu\n", strlen(s));
7    return 0;
8}
What this line does
Press Run algorithm. The highlight will move through the C code.
Program output
(no output yet)

Check your understanding

Five questions. Pick one answer each, then Check answers. The correct choice turns green.

1. Input Kodin prints:

Five letters.

2. %63s is used to:

Leave room for \0.

3. You could replace strlen with:

Manual walk.

4. sizeof(s) on char s[64] is:

Array size vs string length.

5. Spaces in the input with %s:

%s stops at whitespace.