The Program in C to search a sub-string using pointers inputted by user is given below:
#include<stdio.h>
#include<string.h>
int main() {
char str[100], sub[100];
printf("Enter the string: ");
fgets(str, 100, stdin);
str[strlen(str) - 1] = '\0';
printf("Enter the substring to search: ");
fgets(sub, 100, stdin);
sub[strlen(sub) - 1] = '\0';
char *result = strstr(str, sub);
if (result == NULL)
printf("Substring not found\n");
else
printf("Substring found at position: %ld\n", result - str);
return 0;
}
Output:
Enter the string: codeauri
Enter the substring to search: au
Substring found at position: 4
Pro-Tips💡
It uses the fgets
function to get the string input from the user, strstr
function to search for the substring in the main string.
The strstr
function returns a pointer to the first occurrence of the substring in the main string, or NULL
if the substring is not found.
If the substring is found, the program then prints the message “Substring found at position: %ld\n” to indicate that the substring was found and the position it was found.
The position is calculated by subtracting the address of the main string from the address of the substring found.
If the substring is not found, the program prints “Substring not found”.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.