file-handling · intermediate · ~15 min

Count lines at a level

Iterate lines and test each for a token.

Challenge

Count how many log lines mention a given level, by testing each line for a substring.

Task

Implement int count_level(const char *log, const char *level) that returns how many lines of log contain level as a substring.

Input

  • log: a multi-line string, lines separated by '\n'.
  • level: the token to look for (e.g. "ERROR").

Output

Return the number of lines containing level.

Example

log = "INFO ok\nERROR bad\nERROR worse\nWARN hmm\n"
count_level(log, "ERROR")   ->   2
count_level(log, "INFO")    ->   1
count_level(log, "DEBUG")   ->   0

Edge cases

  • Level not present: 0.
  • Match the token per line, not across the newline boundary.

Input format

log: multi-line string (lines split by '\n'). level: token to find.

Output format

int number of lines containing level.

Constraints

Test each line independently so matches don't span newlines.

Starter code

#include <string.h>

int count_level(const char *log, const char *level) {
    /* TODO */
    return 0;
}

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