How to move a word to the end of a string in C

2 Answers

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

char* move_word_to_end(const char *s, const char *word) {
    char *temp = malloc(strlen(s) + 1);
    strcpy(temp, s);

    char *parts[64];
    int count = 0;

    char *token = strtok(temp, " ");
    while (token != NULL) {
        parts[count++] = token;
        token = strtok(NULL, " ");
    }

    int pos = -1;
    for (int i = 0; i < count; i++) {
        if (strcmp(parts[i], word) == 0) {
            pos = i;
            break;
        }
    }

    if (pos != -1) {
        char *t = parts[pos];
        for (int i = pos; i < count - 1; i++)
            parts[i] = parts[i + 1];
        parts[count - 1] = t;
    }

    // allocate result
    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(temp);
    
    return result;
}

int main() {
    char s[] = "Would you like to know more? (Explore and learn)";
    char *out = move_word_to_end(s, "like");
    
    printf("%s\n", out);
    
    free(out);
    
    return 0;
}



/*
run:

Would you to know more? (Explore and learn) like

*/

 



answered Feb 3 by avibootz
edited Feb 3 by avibootz
0 votes
#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_word_to_end(const char *s, const char *word) {
    char *parts[64];
    char *copy;
    int count = split_words(s, parts, 64, &copy);

    int pos = -1;
    for (int i = 0; i < count; i++) {
        if (strcmp(parts[i], word) == 0) {
            pos = i;
            break;
        }
    }

    if (pos != -1) {
        char *t = parts[pos];
        for (int i = pos; 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_word_to_end(s, "like");
    
    printf("%s\n", out);
    free(out);
    
    return 0;
}



/*
run:

Would you to know more? (Explore and learn) like

*/

 



answered Feb 3 by avibootz
...