I'm trying to find a code to check the occurrences of the word or string
I wrote my own code but it's not working can you please help and fix my code
#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100 // 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++;
break;
}
else
{
i++;
cursor++;
}
}
else
{
i = 0;
cursor++;
}
}
printf("Total occurrences of %d", count2);
return 0;
}
#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100 // 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++;
//break; // Commented this line to correct the code.
}
else
{
i++;
cursor++;
}
}
else
{
i = 0;
if(count1 == 0){
cursor++;
}
count1=0;
}
}
printf("Total occurrences of %d", count2);
return 0;
}
You added a break statement inside the if statement which checks if count1 == searchLen. We go inside the if statement whenever we find the string to be searched. But if we put a break inside the if, we break out of the outer for loop and stop the search. So we get only one occurence even if there are more than one occurence as we stop searching as soon as we find one occurence due to the break statement. Commenting the break statement corrects the code.
In the last else statement, we do cursor++ only when count1 = 0, else we dont, as the current character should not be skipped as it can be the first character of the string to be searched.
I would be happy to resolve any queries in the comments. Please consider dropping an upvote to help out a struggling college kid :)
Happy Coding !!
Get Answers For Free
Most questions answered within 1 hours.