C: Reverse each word

Reverse every word of a line, leaving the words in order.

What to build

A program that changes a string in place.

Requirements

  • Read one line.
  • Reverse the letters of each word, keeping the words in their original order.

Input

One line of words separated by single spaces.

Output

One line.

Constraints

The line has from 1 to 200 characters.

Example

Input:

hello world

Output:

olleh dlrow

Why it works

Swapping from both ends of each word needs no second array. The end of a word is either a space or the terminating '\0', so one test finds both.

Examples

Example 1 · Input
hello world
Expected output
olleh dlrow
Example 2 · Input
a
Expected output
a

Hints

Hint 1

Read the line with fgets, and remove the newline at the end.

Hint 2

Find where each word starts and ends, and swap its characters inwards.

Hint 3

The '\0' also ends the last word.

Solution

Show one correct solution (try it yourself first)
#include <stdio.h>
#include <string.h>

int main(void) {
    char line[256];
    fgets(line, sizeof line, stdin);
    line[strcspn(line, "\n")] = '\0';
    int start = 0;
    for (int i = 0; ; i++) {
        if (line[i] == ' ' || line[i] == '\0') {
            int a = start, b = i - 1;
            while (a < b) {
                char t = line[a];
                line[a] = line[b];
                line[b] = t;
                a++;
                b--;
            }
            start = i + 1;
            if (line[i] == '\0') {
                break;
            }
        }
    }
    printf("%s\n", line);
    return 0;
}

Lesson: Strings are char arrays →