BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

C Program to Search Substring in a given String

By Chaitanya Singh | Filed Under: C Programs

In this article, you will learn how to write a C program to search a substring in a given string.

Program to check if substring is present in the given string or not

Here we have a string represented by string array str[] and a substring represented by substr[]. Both of these strings are entered by the user. We are using while loop to search whether the entered substring is present in the given string or not.

If the substring is found, the flag variable is set to 1 else it is set to 0. At the end of the program, if the flag is 1, program prints a message “Substring is found in the entered string” else program prints this message “Substring is found in the entered string”.

#include<stdio.h>
int main()
{
  char str[80], substr[10];
  int count1 = 0, count2 = 0, i, j, flag;

  //user enters the string
  printf("Enter a string: ");
  scanf("%s", str);
  //user enters the substring
  printf("Enter a substring to search: ");
  scanf("%s", substr);

  //'\0' represents the end of the string
  while (str[count1] != '\0')
    count1++;
  while (substr[count2] != '\0')
    count2++;
  for (i = 0; i <= count1 - count2; i++)
  {
    for (j = i; j < i + count2; j++)
    {
      flag = 1;
      if (str[j] != substr[j - i])
      {
        flag = 0;
        break;
      }
    }
    if (flag == 1)
    break;
  }
  if (flag == 1)
    printf("Substring is found in the entered string");
  else
    printf("Substring is not found in the entered string");

  return 0;
}

Output 1:
Search substring in a string output1
Output 2:
Search substring in a string output2
Output 3: As you can see this program is case sensitive, substring book is present in the given string, however due to the uppercase letter ‘B’ the program resulted in a “substring not found” response.
Search substring in a string output3

Related C Programs:

  • C Program to find the frequency of characters in a string
  • C Program to count vowels and consonants in a string using pointer
  • C Program to print String using Pointer
  • C Program to convert lowercase string to uppercase
❮ C ProgrammingC Programs ❯

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Programs

  • C Programs
  • Java Programs
  • C++ Programs

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap