C Find Substring Program
The "Find Substring" program in C is designed to search for a specific substring within a larger string and determine its position (index) within that string. This is a common task in string manipulation and involves comparing portions of the larger string with the substring.
Implementation of Find Substring Program
Here’s a simple implementation of this program in C:
Explanation of the Program
Header Files:
#include <stdio.h>
: For standard input and output functions.#include <string.h>
: For string manipulation functions, especiallystrstr()
.
Variable Declarations:
char str[100]
: An array to hold the main string (up to 99 characters).char sub[50]
: An array to hold the substring (up to 49 characters).char *pos
: A pointer that will point to the location of the substring in the main string.int index
: An integer to store the index of the found substring.
User Input:
- The program prompts the user to enter the main string and the substring. It uses
fgets()
to read both strings, allowing for spaces.
- The program prompts the user to enter the main string and the substring. It uses
Remove Newline Character:
- The newline character introduced by
fgets()
is removed usingstrcspn()
.
- The newline character introduced by
Finding the Substring:
- The
strstr()
function is used to find the first occurrence of the substring within the main string. It returns a pointer to the start of the substring if found; otherwise, it returnsNULL
.
- The
Check for Substring:
- An
if
statement checks whetherpos
is notNULL
. If it is notNULL
, it means the substring was found.
- An
Calculate Index:
- The index of the substring is calculated by subtracting the address of the main string from the address of the substring pointer (
pos
).
- The index of the substring is calculated by subtracting the address of the main string from the address of the substring pointer (
Display Results:
- The program prints the index of the first occurrence of the substring if found; otherwise, it indicates that the substring was not found.
How to Run the Program
Compile the Code: Use a C compiler like
gcc
to compile the code.Execute the Program:
Input Data: Enter the main string and the substring when prompted.
Example Input/Output
Input:
Output:
Conclusion
The "Find Substring" program in C demonstrates how to search for a substring within a string using pointers and the standard library function strstr()
. This program is fundamental in understanding string manipulation, memory addressing, and how to work with character arrays in C. It can be extended to find all occurrences of the substring or to perform case-insensitive searches with additional logic.