basics · beginner · ~15 min

Last character

Find the end of a string.

Challenge

Return the final character of a string before its NUL terminator.

Task

Implement char last_char(const char *s) that returns the last character of s (the one just before the terminating NUL), or '\0' if s is empty. No main — the grader calls it.

Input

A NUL-terminated string s.

Output

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

Example

last_char("hello")   ->   'o'
last_char("x")       ->   'x'
last_char("")        ->   '\0'

Edge cases

  • The empty string has no last character, so return '\0'.

Input format

A NUL-terminated string s.

Output format

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

Constraints

s is a null-terminated string. If empty (""), returns '\0'. Never NULL in tests.

Starter code

#include <string.h>

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

Common mistakes

Accessing index strlen(s) instead of strlen(s) - 1, reading past the end into the null terminator.

Edge cases to handle

Empty string "", single-character string, string with spaces at the end.

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