0

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;
}
Jongware
  • 22,200
  • 8
  • 54
  • 100
Goran Zooferic
  • 371
  • 8
  • 23
  • Are you trying to split the sentence in different words and then compare them to find equal words? And what is, exactly the error? – terence hill Nov 16 '15 at 11:23
  • `iarr` is a `char*` so `si = sizeof(iarr)/sizeof(char*);` is not what you want. you have to wall several time `strtok` till you get a `NULL` – Ôrel Nov 16 '15 at 11:47
  • The compiler says "excess elements in char array initializer" for "sit amet" but it's element of arr object. – Goran Zooferic Nov 16 '15 at 11:54

1 Answers1

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;
}
developer
  • 4,744
  • 7
  • 40
  • 55
  • 1
    [`strdup`](http://ideone.com/nsaCoB) is not a Standard C Function. **implicit declaration of function ‘strdup’** – Michi Nov 16 '15 at 12:01