#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int split_words(const char *s, char *parts[], int max_parts, char **copy_out) {
char *copy = malloc(strlen(s) + 1);
strcpy(copy, s);
int count = 0;
char *token = strtok(copy, " ");
while (token && count < max_parts) {
parts[count++] = token;
token = strtok(NULL, " ");
}
*copy_out = copy; // caller must free(*copy_out)
return count;
}
char* move_nth_word_to_end_of_string(const char *s, int n) {
char *parts[64];
char *copy;
int count = split_words(s, parts, 64, ©);
if (n >= 0 && n < count) {
char *t = parts[n];
for (int i = n; i < count - 1; i++)
parts[i] = parts[i + 1];
parts[count - 1] = t;
}
char *result = malloc(strlen(s) + 1);
result[0] = '\0';
for (int i = 0; i < count; i++) {
strcat(result, parts[i]);
if (i < count - 1) strcat(result, " ");
}
free(copy);
return result;
}
int main() {
char s[] = "Would you like to know more? (Explore and learn)";
char *out = move_nth_word_to_end_of_string(s, 2);
printf("%s\n", out);
free(out);
return 0;
}
/*
run:
Would you to know more? (Explore and learn) like
*/