Reputation: 15
I got a almost good working program to count words from standard input. The word what has to be count is a program argument.
The problem is that I use a white space to see a word but I also must count within th word itself. Example: if my input is aa aaaa #EOF, and I want to count aa the result should be 4. My code result 2.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>
int word_cnt(const char *s, char *argv[])
{
int cnt = 0;
while(*s != '\0')
{
while(isspace(*s))
++s;
if(*s != '\0')
{
if(strncmp(s, argv[1], strlen(argv[1])) == 0)
++cnt;
while(!isspace(*s) && *s != '\0')
++s;
}
}
return cnt;
}
int main(int argc, char *argv[])
{
char buf[1026] = {'\0'};
char *p="#EOF\n";
int tellen = 0;
if (argc != 2)
{
printf("Kan het programma niet uitvoeren, er is geen programma argument gevonden\n");
exit(0);
}
while((strcmp(buf, p) !=0))
{
fgets (buf, 1025, stdin);
tellen += word_cnt(buf, argv);
}
printf("%d", tellen);
return 0;
}
Upvotes: 1
Views: 344
Reputation: 108986
Try strncmp() in a loop.
/* UNTESTED */
unsigned wc(const char *input, const char *word) {
unsigned count = 0;
while (*input) {
if (strncmp(input, word, strlen(word)) == 0) count++;
input++;
}
return count;
}
Upvotes: 1
Reputation: 1304
int word_cnt(const char *s, char *argv[])
{
int cnt = 0;
int len = strlen(argv[1]);
while(*s)
{
if(strncmp(s, argv[1], len) == 0)
++cnt;
++s;
}
return cnt;
}
Upvotes: 2
Reputation: 12985
Where you have this:
if(strncmp(s, argv[1], strlen(argv[1])) == 0)
++cnt;
while(!isspace(*s) && *s != '\0')
++s;
Try this:
/* if it matches, count and skip over it */
while (strncmp(s, argv[1], strlen(argv[1])) == 0) {
++cnt;
s += strlen(argv[1]);
}
/* if it no longer matches, skip only one character */
++s;
Upvotes: 3