Skip to main content

first_word — Display First Word of a String

Allowed functions: write

Write a program that takes a string and displays its first word, followed by a newline.

A word is a section of string delimited by spaces/tabs or by the start/end of the string.

If the number of parameters is not 1, or if there are no words, simply display a newline.

Examples

$> ./first_word "FOR PONY" | cat -e
FOR$
$> ./first_word "this ... is sparta, then again, maybe not" | cat -e
this$
$> ./first_word " " | cat -e
$
$> ./first_word "a" "b" | cat -e
$
$> ./first_word " lorem,ipsum " | cat -e
lorem,ipsum$

Solution

Download first_word.c
#include <unistd.h>

int main(int c, char **v) {

if (c != 2) {

write(1, "\n", 1);
return 0;
}

char *s = v[1];
while (*s == ' ' || *s == '\t')
s++;
while (*s && *s != '\t' && *s != ' ') {
write(1, s, 1);
s++;
}

write(1, "\n", 1);

return 0;
}

How It Works

Goal: Display the first word of a string, skipping leading whitespace.

Approach: Use pointer iteration to skip spaces/tabs, then print characters until the next whitespace or end of string.

Step by step:

  1. If argument count is not 2, print a newline and exit early.
  2. Set a pointer to the start of the string and advance it past any leading spaces or tabs.
  3. Loop through characters, writing each one, until a space, tab, or null terminator is reached.
  4. Print a trailing newline.

Key concept: Pointer iteration and whitespace skipping — advancing a pointer through a string to bypass unwanted characters before processing.