#include
#include
#define MAX_SIZE 1300 // Maximum string size
int main()
{
char str[MAX_SIZE];
char tosearch[MAX_SIZE];
printf("Enter any string: ");
gets(str);
printf("Enter word to search occurrences: ");
gets(tosearch);
int cursor = 0;
int i = 0;
int stringLen = 0;
int searchLen = 0;
int count1;
int count2;
stringLen = strlen(str);
searchLen = strlen(tosearch);
count1 = 0;
count2 = 0;
for (cursor = 0; cursor <= stringLen; )
{
if (str[cursor] == tosearch[i])
{
count1++;
if (count1 == searchLen)
{
count2++;
i = 0;
count1 = 0;
cursor++;
}
else
{
i++;
cursor++;
}
}
else
{
i = 0;
cursor++;
}
}
printf("Total occurrences of %d", count2);
return 0;
}
I have to find the occurrences of the string or word
and this is my code
but in just one cases this code is not working
if you enter ccanada in str[] and canada in tosearch[] the total count is printed as 0 instead of 1 becuase the first c and c is equal so the
i++; cursor++; got worked so the next you get to compare 'c' to 'a' instead of 'c' to 'c'
I have edited your C code and now it is working properly in all test cases. There was only one condition missing and I have added it in the code. I hope it will resolve all issues. The code is provided below :
C Code
#include<stdio.h>
#include<string.h>
#define MAX_SIZE 1300 // Maximum string size
int main()
{
char str[MAX_SIZE];
char tosearch[MAX_SIZE];
printf("Enter any string: ");
gets(str);
printf("Enter word to search occurrences: ");
gets(tosearch);
int cursor = 0;
int i = 0;
int stringLen = 0;
int searchLen = 0;
int count1;
int count2;
stringLen = strlen(str);
searchLen = strlen(tosearch);
count1 = 0;
count2 = 0;
for (cursor = 0; cursor <= stringLen; )
{
if (str[cursor] == tosearch[i])
{
count1++;
if (count1 == searchLen)
{
count2++;
i = 0;
count1 = 0;
cursor++;
}
//edited code
else
{
if(str[cursor]!=str[cursor+1])
{
i++;
cursor++;
}
else
i--;
}
}
else
{
i = 0;
cursor++;
}
}
printf("Total occurrences of %d", count2);
return 0;
}
EXPLANATION : In the first else part of the code(marked bold), i++; cursor++; need to be executed only if the consecutive alphabet of the string are not equal. Hence, I have written them in the if statement with condition str[cursor]!=str[cursor+1]. Hence if condition will only get executed when the consecutive alphabet of the string are not equal.
In the else part of this if statement I have decremented the value of i by 1 so that instead of comparing with the next index, the comparison would be done with the previous index.
SAMPLE OUTPUTS :
NOTE : If you still have any doubt/query regarding the above solution then let me know in the comment. If it helps, do give an upVote to this answer.
Get Answers For Free
Most questions answered within 1 hours.