linux-sysprog · intermediate · ~15 min

Count command arguments

Tokenise a command line.

Challenge

Before a shell can build an argv for exec, it splits the command line into tokens on whitespace. Count those tokens.

Task

Implement int count_args(const char *line) that returns the number of whitespace-separated tokens in line. Treat runs of spaces or tabs as a single separator; ignore leading and trailing whitespace.

Input

  • line: a command-line string.

Output

The number of tokens.

Example

count_args("ls -l /tmp")      ->   3
count_args("  echo   hi  ")   ->   2
count_args("")                ->   0

Edge cases

  • Empty or all-whitespace string: return 0.
  • Multiple spaces/tabs between tokens count as one separator.

Input format

line: a command-line string (spaces and tabs separate tokens).

Output format

Number of whitespace-separated tokens.

Constraints

Runs of whitespace collapse; leading/trailing whitespace ignored.

Starter code

int count_args(const char *line) {
    /* TODO */
    return 0;
}

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