basics · beginner · ~15 min

Count format specifiers

Scan a format string handling the `%%` escape.

Challenge

Count the conversion specifiers in a printf-style format string.

Task

Implement int count_format_specs(const char *fmt) that returns how many conversion specifiers fmt contains. A specifier is a % followed by any non-% character. The literal %% (an escaped percent sign) does not count and consumes both characters. No main — the grader calls it.

Input

A NUL-terminated format string fmt.

Output

Returns the number of conversion specifiers, as an int.

Example

count_format_specs("%d and %s")   ->   2
count_format_specs("%d%d%d")      ->   3
count_format_specs("100%% done")  ->   0     (%% is a literal percent)
count_format_specs("")            ->   0

Edge cases

  • %% counts as zero specifiers and skips both characters.
  • A trailing lone % (nothing after it) is not a specifier.

Input format

A NUL-terminated format string fmt.

Output format

The count of conversion specifiers, as an int.

Constraints

%% is a literal percent and does not count.

Starter code

int count_format_specs(const char *fmt) {
    /* TODO */
    return 0;
}

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