Coding Practice

Write a C Program to check if a Substring is present in the given String

Check String to Substring

3. Write a C Program to check if a Substring is present in the given String.

Sample Input Sample Output
String: Bangladesh
Substring: lad
Match found
String: Paragraph
Substring: rag
Match found
String: America
Substring: rice
Not Match found

Sample Output
String: Bangladesh
Substring: lad

Match found


Process returned 0 (0x0)   execution time : 11.043 s
Press any key to continue.
Source Code
#include<stdio.h>
#include<string.h>
 
int main()
{
    int i, j, temp, count = 0, count2 = 0;
    char str[50], subString[20];
 
    printf("String: ");
    gets(str);
 
    printf("Substring: ");
    gets(subString);
 
    while (str[count] != '\0')
    {
        count++;
    }
    while (subString[count2] != '\0')
    {
        count2++;
    }
 
    for (i = 0; i <= count - count2; i++)
    {
        for (j = i; j < i + count2; j++)
        {
            temp = 1;
            if (str[j] != subString[j - i])
            {
                temp = 0;
                break;
            }
        }
        if (temp == 1)
            break;
    }
    if (temp == 1)
    {
        printf("\nMatch found\n\n");
    }
    else
    {
        printf("\nNo match found\n\n");
    }
    return 0;
}
Sample Output
String: America
Substring: rice

No match found


Process returned 0 (0x0)   execution time : 12.346 s
Press any key to continue.

No comments:

Post a Comment

Change Theme
X