Ads by ProfitSence

Check substring exists in a string in C

Last Updated on Wednesday 5th Oct 2022

Check if string contains substring c.

C Find subString


  • Returns a pointer to the first occurrence of str2 in str1, or a null pointer if str2 is not part of str1.
  • The matching process does not include the terminating null-characters, but it stops there.


  • str1 - C string to be scanned.
  • str2 - C string containing the sequence of characters to match.

Find subString in C

					#include <stdio.h>

#include <string.h>

int main() {
  char str[] = "This is a simple string";
  char * simp;
  simp = strstr(str, "simple");
  if (simp != NULL)
    strncpy(simp, "sample", 6);
  return 0;

					// This is a sample string


Find subString in String C

					#include <stdio.h>

#include <string.h>

int main(void) {
  char mainstring[] = "Hello World";
  char substring[20], * ret;
  int i = 0;
  puts("Enter the subString to find");
  fgets(substring, sizeof(substring), stdin);
  substring[strlen(substring) - 1] = '\0';
  ret = strstr(mainstring, substring);
  if (strcmp((ret = strstr(mainstring, substring)), substring)) {
    printf("subString is present\t");
  printf("And the subString is:::");

  for (i = 0; i < strlen(substring); i++) {
    printf("%c", *(ret + i));

  return 0;

					Enter the subString to find
And the subString is:::World