C Online Compiler
Example: Find Substring Example in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Find Substring Example #include <stdio.h> #include <string.h> // Required for strstr() int main() { // Step 1: Declare the main string and the substring to find char mainStr[] = "The quick brown fox jumps over the lazy dog."; char subStr1[] = "fox"; char subStr2[] = "cat"; // Substring not in main string // Step 2: Find the substring using strstr() char *resultPtr1 = strstr(mainStr, subStr1); char *resultPtr2 = strstr(mainStr, subStr2); // Step 3: Print results based on whether the substring was found if (resultPtr1 != NULL) { printf("Substring \"%s\" found at position: %ld\n", subStr1, resultPtr1 - mainStr); printf("Part of string from \"fox\": %s\n", resultPtr1); } else { printf("Substring \"%s\" not found.\n", subStr1); } if (resultPtr2 != NULL) { printf("Substring \"%s\" found at position: %ld\n", subStr2, resultPtr2 - mainStr); } else { printf("Substring \"%s\" not found.\n", subStr2); } return 0; }
Output
Clear
ADVERTISEMENTS