basics · beginner · ~15 min

First character

Index into a char array and handle the empty case.

Challenge

Return the first character of a string, treating the empty string safely.

Task

Implement char first_char(const char *s) that returns the first character of s, or '\0' if s is empty. No main — the grader calls it.

Input

A NUL-terminated string s.

Output

Returns the first character, or '\0' (0) when s is empty.

Example

first_char("hi")   ->   'h'
first_char("x")    ->   'x'
first_char("")     ->   '\0'

Edge cases

  • The empty string starts with '\0', so s[0] already covers it.

Input format

A NUL-terminated string s.

Output format

The first character, or '\0' if s is empty.

Starter code

char first_char(const char *s) {
    /* TODO */
    return 0;
}

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