Reputation: 1533
I'm trying to write a function that gets two strings, a short string called str1, and a longer one called str2.
the function will count how many times is str1 found in str2.
example: str1= 'ab' str2 = 'abab' print 2
but for some reason, for the above example. i get 3. This is my code:
int how_many_times(char* str1,char* str2)
{
int result=0,i,j=0;
for(i=0;i<strlen(str2);i++)
{
if((str1[i]==str2[j]))
{
while(str1[i]==str2[j])
{
j++;
if(j==strlen(str1))
{
result++;
j=0;
}
i++;
}
}
else
i++;
}
printf("%d",result);
getch();
return result;
}
Upvotes: 2
Views: 1337
Reputation: 542
I came up with this (doesn't use strstr, but does use strlen):
int how_many_times(char *str, char *str2) {
int result = 0, i = 0, j, k, len = strlen(str);
while(str2[i]) {
j = 0;
k = 0;
while(1) {
if(str[j + k] == str2[i + k] && str[j] != 0) {
if(j + k == len - 1) {
result++;
break;
}
} else {
break;
}
k++;
}
i++;
}
return result;
}
Upvotes: 1
Reputation: 726699
Since this is likely a learning exercise, I would not suggest using a library function, assuming that you would rather fix your code.
Your code is close to working:
i
and j
in the code that accesses str[...]
- you need to access str1
with j
and str2
with i
, not the other way around, because i
goes up to strlen(str2)
and j
goes up to strlen(str1)
j
to zero when you find a mismatch - The else
branch of the if
needs to reset j
after a partial match has been found.Here is your modified code running on ideone.
int how_many_times(char* str1,char* str2)
{
int result=0,i,j=0;
for(i=0;i<strlen(str2);i++)
{
if((str1[j]==str2[i])) // <<<=== Swapped i and j
{
while(str1[j]==str2[i]) // <<<=== Swapped i and j
{
j++;
if(j==strlen(str1))
{
result++;
j=0;
}
i++;
}
}
else {
i++;
j = 0; // <<<=== Added
}
}
return result;
}
P.S. Library-based solution is better :-)
Upvotes: 2
Reputation: 1284
The strstr function returns a pointer to the first occurrence of a string within another. We can use this to count the number of occurrences by incrementing a variable count
until the function returns NULL.
int countOccur(char *a, char *b) {
int count = 0;
while (b = strstr(b, a)) {
count++;
b++;
}
return count;
}
Upvotes: 1
Reputation: 2930
int count(char *s1, char *s2)
{
char *p;
int c;
c = 0;
for (p = strstr(s2, s1); p; p = strstr(p, s1)) {
c++;
p++;
}
return c;
}
Upvotes: 3