Check substring exists in a string in C

Last Updated On Monday 18th Oct 2021

Check if string contains substring c.

C Find subString

strstr

  • 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.

Parameters

  • 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);
  puts(str);
  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));

  }
  puts("\n");
  return 0;
}
	
	Enter the subString to find
World
And the subString is:::World
	

References