A PHP Error was encountered

Severity: 8192

Message: str_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated

Filename: libraries/Filtered_db.php

Line Number: 23

C program to check whether a substring is present in a given string
Q:

C program to check whether a substring is present in a given string

0

C program to check whether a substring is present in a given string

In this program, we will learn how to check whether a substring is present in a string or not without using library function?

We are implementing a function named myStrStr() this function will return 1 if substring present in the string and return 0, if substring is not present in the string.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program to check substring in a string in C

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

//function declaration
int myStrStr(char* str, char* sub);

int main()
{
    char str[100] = { 0 };
    char strTocheck[10] = { 0 };

    printf("Enter complete string: ");
    scanf("%[^\n]s", str);
    getchar();

    printf("Enter string to check: ");
    scanf("%[^\n]s", strTocheck);

    if (myStrStr(str, strTocheck))
        printf("String "%s" found in "%s"\n", strTocheck, str);
    else
        printf("String "%s" not found in "%s"\n", strTocheck, str);

    return 0;
}

//function definition
int myStrStr(char* str, char* sub)
{
    int flag = 0;

    int i = 0, len1 = 0, len2 = 0;

    len1 = strlen(str);
    len2 = strlen(sub);

    while (str[i] != '\0') {
        if (str[i] == sub[0]) {
            if ((i + len2) > len1)
                break;

            if (strncmp(str + i, sub, len2) == 0) {
                flag = 1;
                break;
            }
        }
        i++;
    }

    return flag;
}

Output

First run:
Enter complete string: Hello how are you?
Enter string to check: how
String "how" found in "Hello how are you?"

Second run:
Enter complete string: Hello how are you?
Enter string to check: we
String "we" not found in "Hello how are you?"

Third run:
Enter complete string: Hello how are you?
Enter string to check: how are you?
String "how are you?" found in "Hello how are you?"

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now