I am trying to implement the question 8.16 from the C How to program. The question is below:
(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.].
Here is my code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define SIZE 128
int main(void){
char s[SIZE], search_string[SIZE];
char *searchPtr;
fgets(s, SIZE, stdin);
fgets(search_string, SIZE, stdin);
searchPtr = strstr(s, search_string);
//printf("%s", searchPtr);
if(searchPtr){
printf("%s%s\n", "The text line beginning with the first occurrence of: ", search_string);
searchPtr = strstr(searchPtr+1, search_string);
if(searchPtr){
printf("%s%s\n","The text line beginning with the second occurrence of: ", search_string);
} else{
printf("%s", "The string to be searched just appeared once.\n");
}
} else {
printf("Search string is not found in the string.");
}
}
Here is my input for string s:
hello world world
Here is my input for search_string:
world
Here is my output
The text line beginning with the first occurrence of: world The string to be searched just appeared once.
But output should have been
The text line beginning with the first occurrence of: world
The text line beginning with the first occurrence of: world