Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Please help. The code must be in C programming language (not C ++ or java etc) 8

ID: 3681120 • Letter: P

Question

Please help. The code must be in C programming language (not C ++ or java etc)

8.16 (Searching for Substrings) Write a program that inputs a line of text and a search string
from the keyboard. Using function strstr, locate the first occurrence of the search string in the line
of text, and assign the location to variable searchPtr of type  char *. If the search string is found,
print the remainder of the line of text beginning with the search string . Then, use strstr again to
locate the next occurrence of the search string in the line of text. If a second occurrence is found,
print the remainder of the line of text beginning with the second occurrence. [Hint: The second call
to strstr should contain searchPtr + 1 as its first argument . Also, remember to include the C string
header to use the strstr function.]

Note: assume that a line of text is no longer than 80 characters .

Explanation / Answer

#include <stdio.h>
#include <string.h>

int main(void)
{
char text[80];
char search[15];
char *searchPtr;

/* get the line of text from the user */
printf("Enter a line of text: ");
gets(text);

/* get the search string from the user */
printf("Enter a search string: ");
scanf("%s", search);

/* search for the search string in the line of text */
searchPtr = strstr(text, search);

/* if it is found */
if (searchPtr)
{
/* display the sentence from the search string on */
printf(" The remainder of the line beginning with ");
printf("the first occurrence of %s: ", search);
printf("%s ", searchPtr);

/* search for the search string in the remainder of the sentence */
searchPtr = strstr(searchPtr + 1, search);

/* if it is found */
if (searchPtr)
{
/* display the sentence from the second occurrence of the search string on */
printf(" The remainder of the line beginning with ");
printf("the second occurrence of %s: ", search);
printf("%s ", searchPtr);
}
else
printf("The search string appeared only once. ");
}
else
printf(""%s" not found. ", search);

return 0;
}

OUTPUT:

Test1:
Enter a line of text:
The only thing we have to fear is fear itself.
Enter a search string: fear

The remainder of the line beginning with
the first occurrence of fear:
fear is fear itself.

The remainder of the line beginning with
the second occurrence of fear:
fear itself.

Test2:
Enter a line of text:
The quick brown fox jumped over the lazy dog.
Enter a search string: brown

The remainder of the line beginning with
the first occurrence of brown:
brown fox jumped over the lazy dog.
The search string appeared only once.

Test3:
Enter a line of text:
Four score and seven years ago
Enter a search string: Three
"Three" not found.