#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
*/