C Program to Search a Substring Using strstr() (strstr() Function in C Language)
The strstr() function in C is used to find the first occurrence of a substring within another string. It returns a pointer to the first occurrence of the substring. If the substring is not found, it returns NULL.
The strstr() function is declared in the <string.h> header file.
C भाषा में strstr() फंक्शन का उपयोग किसी String के अंदर दूसरी String (Substring) को खोजने के लिए किया जाता है। यह Substring की पहली occurrence का Pointer Return करता है। यदि Substring नहीं मिलती, तो यह NULL Return करता है।
Syntax
strstr(string, substring);Example:
char str[] = "Welcome to C Programming";char *ptr = strstr(str, "C");if (ptr != NULL)printf("Substring found: %s", ptr);elseprintf("Substring not found");
Output:
Substring found: C ProgrammingC Program Using strstr() Function
निम्नलिखित C Program में strstr() फंक्शन की सहायता से एक String के अंदर दूसरी String खोजी जाती है।
#include <stdio.h>#include <string.h>int main(){char str[100], sub[50];char *ptr;printf("Enter a string: ");fgets(str, sizeof(str), stdin);str[strcspn(str, "\n")] = '\0';printf("Enter substring to search: ");fgets(sub, sizeof(sub), stdin);sub[strcspn(sub, "\n")] = '\0';ptr = strstr(str, sub);if (ptr != NULL)printf("Substring found: %s", ptr);elseprintf("Substring not found");return 0;}
Output
Enter a string: Welcome to C ProgrammingEnter substring to search: CSubstring found: C Programming
Explanation
strstores the main string, whilesubstores the substring to search.strमें Main String औरsubमें खोजी जाने वाली Substring स्टोर होती है।fgets()accepts both strings from the user.fgets()यूजर से दोनों Strings इनपुट लेता है।strstr(str, sub)searches for the first occurrence ofsubinstr.यहstrमेंsubकी पहली Occurrence खोजता है।- If the substring is found,
ptrpoints to its first occurrence; otherwise, it containsNULL.Substring मिलने परptrउसके पहले स्थान को दर्शाता है, अन्यथा इसमेंNULLहोता है।
Important Points
strstr()is declared in<string.h>.It searches for a substring inside another string.
It returns a pointer to the first occurrence.
It returns
NULLif the substring is not found.The search is case-sensitive.
महत्वपूर्ण बिंदु:
strstr()फंक्शन<string.h>में Defined है।यह एक String में दूसरी String को खोजता है।
यह पहली Occurrence का Pointer Return करता है।
Substring नहीं मिलने पर
NULLReturn करता है।यह Case-Sensitive होता है।
Comments
Post a Comment