file-handling · beginner · ~15 min

Count lines from a string buffer

Streaming character classification without I/O.

Challenge

Count the lines in text you have already loaded into memory, by tallying newline characters.

Task

Implement size_t buffer_line_count(const char *buf) that returns how many '\n' characters appear in the NUL-terminated string buf.

Input

buf — a NUL-terminated C string (the in-memory contents of a file). It may be empty.

Output

The number of '\n' bytes in buf, as a size_t.

Example

"a\nb\nc\n"   ->   3
"a\nb"        ->   1
""            ->   0

Edge cases

  • Empty string returns 0.
  • A final line with no trailing newline is NOT counted (only '\n' bytes are tallied).

Input format

buf: a NUL-terminated string holding file contents (may be empty).

Output format

size_t count of '\n' characters in buf.

Constraints

Count newline bytes only; do no I/O.

Starter code

#include <stddef.h>
size_t buffer_line_count(const char *buf) { /* TODO */ return 0; }

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.