Question
The following code finds all occurrences of one string in another string and prints out the index at which each occurrence of the string occurs.
The following code finds all occurrences of one string in another string and prints out the index at which each occurrence of the string occurs. For example, in the string: "the cat ran the race" It would say that the word "the" was found in positions 0 and 12. Unfortunately, some bugs have crept into the code and need to be found and corrected. You should take the version of the code you have been given and use your debugging skills (on a compiler) to find the four (4) bugs in the code and fix them.
For each bug you find and correct you should:
- Write the original line number on which you found the bug
- Explain what was wrong with this line - Explain what you did to fix the bug
- Show the original line(s) of code with the bug in it
- Show your fixed line(s) of code that corrects the bug
#include
#include
#define MAX_POSITIONS 34
int findStr(const char words[], const char str[]);
int findWords(const char words[], const char str[], int positions[]);
int main(void) { char str[] = { "You say what I say sometimes." };
char lookFor[] = { "say" };
int foundIn[MAX_POSITIONS] = { 0 }; int numberFound = 0, i;
numberFound = findWords(lookFor, str, foundIn);
printf("%s found in positions: ", lookFor);
for (i = 0; i < numberFound; ++i) {
printf("%d%s", foundIn[i], (i == (numberFound - 1) ? " " : ", "));
}
return 0;
}
int findStr(const char words[], const char str[])
{
int i, j, found = 0, matches = 0, posn = -1; int len = strlen(str);
for (i = 0; !found && str[i] != '\0'; i++) { if (words[i] == str[0]) {
matches = 1;
for (j = 1; words[i + j] != '\0' && str[j] == '\0'; j++) {
if (words[i + j] == str[j]) { matches++; }
}
if (matches = len) { found = 1; posn = i; }
} } return posn; }
int findWords(const char str[], const char words[], int positions[]) {
int numFound = 0, lastPosn = 0, offset = 0;
do {
offset += lastPosn; lastPosn = findStr(&words[offset], str);
if (lastPosn >= 0) { positions[numFound++] = offset + lastPosn; offset += strlen(str); } }
while (lastPosn >= 0 && offset < strlen(words)); return offset; }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started