String Length in C

Level 391 keystrokes

Calculates string length by counting characters until null terminator.

C code

// "Hello" is stored as 6 chars: H e l l o and the terminator '\0'
1char str[] = "Hello";
// len is both the counter and the index of the next character
2int len = 0;
// Advance until the terminating '\0' is reached
3while (str[len] != '\0') {
// Count one more character
4 len++;
5}
// Prints 5: the '\0' is not counted, the same result as strlen(str)
6printf("%d\n", len);

Output

5
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C code and how often they appear.

  • ;× 4
  • "× 4
  • =× 3
  • '× 2
  • (× 2
  • )× 2
  • [× 2
  • ]× 2
  • \× 2
  • +× 2

More C examples at level 3

← C typing practice