Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,987 questions

51,931 answers

573 users

How to reverse the middle words of a string in C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>

void reverse(char *start, char *end) {
    while (start < end) {
        char tmp = *start;
        *start++ = *end;
        *end-- = tmp;
    }
}

void reverse_middle_words(char *s) {
    char *starts[128];
    char *ends[128];
    int count = 0;

    char *p = s;

    // Scan the string and record word start/end pointers
    while (*p != '\0') {
        // Skip spaces
        while (*p == ' ')
            p++;
        if (*p == '\0')
            break;

        // Mark start of word
        starts[count] = p;

        // Move to end of word
        while (*p != ' ' && *p != '\0')
            p++;

        // Mark end of word (last character)
        ends[count] = p - 1;
        count++;

        if (count >= 128)
            break;
    }

    // Fewer than 3 words → nothing to do
    if (count < 3)
        return;

    // Reverse only middle words
    for (int i = 1; i < count - 1; i++) {
        reverse(starts[i], ends[i]);
    }
}

int main(void) {
    char s[] = "Hello how are you today";

    reverse_middle_words(s);
    printf("%s\n", s);

    return 0;
}



/*
run:

Hello woh era uoy today

*/

 



answered Dec 25, 2025 by avibootz
...