LearnFrenzy
Sign in Take a free test

Strings · String Programs · Question 5

Reverse the words of a sentence in place in C Solution, output & explanation

  • Program
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

Turn "pointers are fun" into "fun are pointers" in place, without a second buffer.

Solution
main.c
#include <stdio.h>
#include <string.h>

static void rev(char *l, char *r) {
    while (l < r) {
        char t = *l;
        *l++ = *r;
        *r-- = t;
    }
}

void reverse_words(char *s) {
    size_t n = strlen(s);
    if (n == 0)
        return;
    rev(s, s + n - 1);                  /* 1. reverse the whole sentence */
    for (char *w = s; *w; ) {           /* 2. reverse each word back */
        while (*w == ' ')
            w++;
        char *e = w;
        while (*e && *e != ' ')
            e++;
        if (e > w)
            rev(w, e - 1);
        w = e;
    }
}

int main(void) {
    char s[] = "pointers are fun";
    reverse_words(s);
    printf("%s\n", s);
    return 0;
}

Output Verified by compiling and running

fun are pointers

Reversing the whole string puts the words in the right order but spelled backwards ("nuf era sretniop"); reversing each word fixes the spelling. O(n) time, O(1) extra space.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Popular