Goran Zooferic
Goran Zooferic

Reputation: 473

Separate and compare same word inside a string in C

How can I separate and compare words inside a sentence as follows? For example, I want to separate "ipsum is that it has ipsum", there is two same words ("ipsum") in this sentence. I'm trying to write followed code but it doesn't work because it failed on array iarr.

int main(void) {
    int i, j, s, si;

    char* iarr, arr[] = {
        "lorem ipsum dolor", 
        "sit amet",
        "ipsum is that it has ipsum"
    };

    s = sizeof(arr)/sizeof(char*);

    for(i=0; i<s; i++){

        iarr = strtok(arr[i]," ");
        si = sizeof(iarr)/sizeof(char*);

        for(j=0; j<si; j++){
            printf("%s\n",iarr[j]);
        }
    }

    return 0;
}

Upvotes: 0

Views: 79

Answers (1)

You should not need si = sizeof(iarr)/sizeof(char*); it is a incorrect instruction because iarr is an char*. strtok make error when you use an const char* as first parameter.

try this solution:

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

int main(void) {
    int i, j, s, si;

    char* iarr;
    char *tmp;
    char* arr[] = {"lorem ipsum dolor", "sit amet", "ipsum is that it has ipsum"};

    s = sizeof(arr)/sizeof(char*);

    for(i=0; i<s; i++){

        tmp = strdup(arr[i]);
        // you should allocate memory for string that you would to cut
        iarr = strtok(tmp, " ");

        while (iarr != NULL)
        {
            printf ("%s\n",iarr);
            iarr = strtok (NULL, " ");
        }
        free(tmp);
        tmp = NULL;

    }

    return 0;
}

Upvotes: 1

Related Questions