I did a quick search on the forums and there was another problem similar to the one i'm trying to solve.
I'm supposed to use the first word of a sentence as a search parameter and check the rest of the string for occurences of the word. If the word appears again, increment a counter.
The problem I'm having is that when I use the function strstr() in a while loop, the console hangs :rolleyes: .
Correct me if i'm wrong, but the strstr() function returns a NULL if the substring isn't found in the main string. So, if my sentence was "the cat sat on the mat" the loop would terminate after the second "the."
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#define SIZE 100
#define FLAG 1
void search_string(char *);
char string[SIZE];
int main(void)
{
char array[SIZE];
puts("Enter a string:");
gets(array);
search_string(array);
return 0;
}
void search_string(char * array)
{
char *ptr, *strptr;
int i = 0, j = 1;
ptr = array;
while (*ptr != '\0')
{
if (isspace(*ptr))
break;
string[i] = array[i]; //put each char from array into string until a space is found.
ptr++;
i++;
}
strptr = strstr(array, string);
/*
while (FLAG == 1)
{
if (strptr != 0)
j++;
else
FLAG == 0;
}
*/
printf("The first word is: %s\n", string);
printf("The sentence is: %s\n", array);
printf("The first word occured %d times in the sentence\n", j);
}