To find the number of occurr in a single string there's not a single
function but it's easy using strstr():
#include <stdio.h>
#include <string.h>
int main( void )
{
char a[ ] = "this is the first string and after is the second string";
char b[ ] = "string";
int cnt = 0;
char *sptr = a;
while ( *sptr != '\0' && ( sptr = strstr( sptr, b ) ) != NULL )
{
cnt++;
sptr += strlen( b );
}
printf( "%d\n", cnt );
return 0;
But please note that the problem is still not completely specified:
what should be the result if you search in for "AA" in the string
"AAAAA"? The above method would return 2, but one also could argue
that it should be 4. To get that result you would have to change
the line
sptr += strlen( b );
to
sptr++;
If you have a number of strings just convert the above into a
function that takes two strings (the string to search in and
the string to search for) as its arguments and returns the
number of occurrences. Then call that function for each of
the strings and add up the results.
Ok and thank You,
I have used your suggestion and I have modified my code in this way:
/*** HERE the various #define ***/
#define BUFLEN 100
struct node
{
char info[BUFLEN] ;
struct node *pun ;
} ;
typedef struct node* mylist ;
/*** HERE the various Prototype ***/
int main(int argc, char *argv[])
{
int occur, n;
mylist testa = NULL ;
char myWord[20];
char mystring[BUFLEN];
/**** HERE the Input code forf mystring and the code inserting each
mystring in the struct****/
/* I search the occurrence number in the entire list */
occur = word_counter(testa, myword, n) ;
printf("The occurrences are: %d\n",occur);
}
int word_counter(mylist p, const char *buf, int n)
{
int occ;
char temp[BUFLEN];
occ = 0;
n = 0;
while (p != NULL)
{
strcpy(temp, p->info);
occ = eachline_counter(temp, buf, j);
n = n + occ;
printf("Occurrences for this string are: %d\n", n ) ;
p = p->pun ;
}
return (n) ;
}
int eachline_counter(char *a, char *b, int rip)
{
int cnt = 0;
char *sptr = a;
while ( *sptr != '\0' && ( sptr = strstr( sptr, b ) ) != NULL )
{
cnt++;
sptr += strlen( b );
}
printf( "%d\n", cnt );
return (cnt);
};
But when I compile the program, the GCC compiler return to me this
error:
Sure, I mistake something; but I don't see the error. Can You help
me ?
Thank You and Best Regards
Gaetano