Hi all,
I'm working on a programming assignment for class and after trying a few things on my own I got stuck. Basically my function will take a string and count the number of times each word in the string occurs in the string. For example this string:
The brown fox jumped over the lazy fox.

Would return something like this:

Words Occurences
----------------------------------------
the 2
brown 1
fox 2
jumped 1
etc.

I was trying to chain together calls to strstr for each word after I tokenized the string, but I know there must be a more elegant method. If anyone could provide me with a tip to get started I would greatly appreciate it.

Matt

What good would strstr do after you have tokenized the string???

Declare a string array and an integer array of some respectable size.

Tokenize the string and assign every string formed to the indexes of string array.Now use the string array indexes and strcmp to find the repetition of a particular string and store the number of repetitions in the integer array and initialize all the repeated strings to null every time you use strcmp.

hmm I'm having some pointer troubles with an array of strings. I can't seem to find my error with the pointers. Here is my code, it compiles fine but segfaults.

int words = numWords(text);
        char *text_tokenized[words];
        //printf("%i", words);
        
        text_tokenized[0] = strtok(text, " ");
        int i;
        for(i = 1; text_tokenized[i] != NULL && i < words; i++) {
        	text_tokenized[i] = strtok(NULL, " ");
        	printf("%s", text_tokenized[i]);
        }

        for(i = 0; i < words; i++)
        {
        	printf("%s", text_tokenized[i]);
        }

I have something that is working better now, if I use malloc i don't get a segfault, but now my program is getting the first string token and the rest as nulls. I don't understand my code looks right:

int words = numWords(text);
        char **text_tokenized = malloc(words*sizeof(char *));
        
        int i = 0;
        text_tokenized[i] = strtok(text, " ");
        for(i = 1; text_tokenized[i] != NULL; i++) {
        	text_tokenized[i] = strtok(NULL, " ");
        	//printf("%s ", strtok(NULL, " "));
        }
        
        for(i = 0; i < words; i++)
        {
        	printf("%s", text_tokenized[i]);
        }

You're gonna kick yourself! Instead of this for(i = 1; text_tokenized[i] != NULL; i++) You mean this: for(i = 1; i < words; i++) {

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.