Search This Blog
Welcome to 1printf(), your ultimate destination for C, C++, Linux, Data Structures, and Microcontroller programming! ๐ ๐นLearn advanced coding techniques in C& C++ ๐นMaster Linux internals & shell scripting ๐นDeep dive into Data Structures & Algorithms ๐นExplore Embedded Systems & Microcontrollers (8051,UART, RTOS) ๐นGet hands-on coding tutorials, project ideas,and interview preparation tips Whether you're a beginner or an experienced programmer, this channel will help you
Featured
- Get link
- X
- Other Apps
C program to implement a custom strstr() function to check if one string is a substring of another
๐ถ Custom strstr() Function in C
#include <stdio.h>
// Custom strstr function
int my_strstr(char *str1, char *str2) {
int i, j;
for (i = 0; str1[i] != '\0'; i++) {
for (j = 0; str2[j] != '\0'; j++) {
if (str1[i + j] != str2[j]) {
break;
}
}
// If full substring matched
if (str2[j] == '\0') {
return 1;
}
}
return 0;
}
int main() {
char str1[100], str2[100];
printf("Enter string1: ");
scanf("%s", str1);
printf("Enter string2: ");
scanf("%s", str2);
if (my_strstr(str1, str2)) {
printf("String2 is a substring of string1\n");
} else {
printf("String2 is not a substring of string1\n");
}
return 0;
}
๐ Explanation:
This C program defines a custom version of the strstr() function to check whether one string is a substring of another.
๐น The outer loop goes through each character of the main string str1.
๐น The inner loop checks if all characters of str2 match starting from current index in str1.
๐น If all characters of str2 match (end of str2 is reached), the function returns 1 (true).
๐น Otherwise, it continues to the next position.
๐น If no match is found by the end of the loop, it returns 0 (false).
๐ Sample Output:
Enter string1: hello
Enter string2: ell
String2 is a substring of string1
Enter string1: openai
Enter string2: bot
String2 is not a substring of string1
๐ท️ Keywords:
custom strstr in C, substring check program, string functions in C, how to check substring manually in C, C interview string question, nested loop string match
Popular Posts
C++ Program for Hybrid Inheritance (All Types Together)
- Get link
- X
- Other Apps
C++ Program for Function Overloading Example
- Get link
- X
- Other Apps
Comments
Post a Comment