Find occurrences of one string in another : String Search « String « C Tutorial






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

int main(void)
{
  char text[100];
  char substring[40];

  printf("\nEnter the string to be searched(less than 100 characters):\n");
  fgets(text, sizeof(text), stdin);

  printf("\nEnter the string sought (less than 40 characters ):\n");
  fgets(substring, sizeof(substring), stdin);

  /* overwrite the newline character in each string */
  text[strlen(text)-1] = '\0';
  substring[strlen(substring)-1] = '\0';

  int i;
  for(i = 0 ; (text[i] = toupper(text[i])) ; i++);
  for(i = 0 ; (substring[i] = toupper(substring[i])) ; i++);

   printf("\nThe second string %s found in the first.",((strstr(text, substring) == NULL) ? "was not" : "was"));
  return 0;
}
Enter the string to be searched(less than 100 characters):
     string
     
     Enter the string sought (less than 40 characters ):
     str
     
     The second string was found in the first.








3.11.String Search
3.11.1.Find occurrences of one string in another