Originally Posted by
whiteflags
userxbw,
Consider removing newlines that fgets() leaves in the string so that they do not affect your results.
yep, I did a total rewrite of that OPs code.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void find_freqs(char sentence[], char word[])
{
// char sentence[1000], word[100];
int snum, wnum, frequency = 0, i, j;
/*
puts("Enter Sentence");
gets(sentence);
puts("Enter word to find its frequency");
gets(word);
*/
snum = strlen(sentence);
wnum = strlen(word);
for (i = 0; i < snum; i++)
{
//printf("sentence[i] %c\n", sentence[i]);
// printf("word %c\n", word[0]);
if (sentence[i] == word[0])
{ printf("words matched?\n");
for (j = 0; j < wnum; j++)
{
if (sentence[i + j] != word[j])
{
break;
}
}
if (j == wnum)
{
frequency++;
}
}
}
printf("The string '%s' occurs %d times \n", word, frequency);
}
int find_freqs_2(char sentence[], char search_word[])
{
int a = 0, b = 0,flaged = 3;
int len = 0, count_times_matched = 0;
char check_word[300];
// chop off \n
search_word[strlen(search_word) - 1] = '\0';
len = strlen(sentence);
while (a != len+1)
{
if ( sentence[a] != ' ')
{
check_word[b] = sentence[a];
b++;
}
else
{
check_word[b] = '\0';
flaged = 0;
}
if (flaged == 0)
{
if ( strcmp(check_word,search_word ) == 0)
count_times_matched++;
memset(check_word, 0, sizeof(check_word[0]));
b=0;
flaged = 1;
}
a++;
}
return count_times_matched;
}
int main (void)
{
char words[300];
char word[100];
printf("Enter sentence\n");
fgets(words, 300,stdin);
// printf("words length %lu\n", strlen(words));
printf("enter word to find many times it shows up\n");
fgets(word, 100, stdin);
// printf("word length %lu\n", strlen(word));
printf("Search word [ %s ] found %d times\n",word, find_freqs_2(words, word) );
//find_freqs(words,word);
return 0;
}
thanks though.seeings how you already gave out the complete answer, I guess it ok for me to post mine (now) hehe
he may now learn their is more then one way to do things.