strstr() in C
×


strstr() in C

38

The strstr function in C is used to locate the first occurrence of a substring within another string.

 It stands for "string search" and is part of the standard C library .

How strstr Works 

 The strstr function takes two parameters: the main string to search within and the substring to search for.

 It scans the main string from left to right, looking for the first occurrence of the substring.

 If found, it returns a pointer to the first character of the substring within the main string.

 If the substring is not found, it returns a null pointer (NULL).

Example:

#include<stdio.h>
#include<string.h>

int main() {
    char mainStr[] = "The quick brown fox jumps over the lazy dog";
    char subStr[] = "brown";

    char *result = strstr(mainStr, subStr);

    if (result != NULL) {
        printf("Substring found at position: %ld\n", result - mainStr);
    } else {
        printf("Substring not found.\n");
    }

    return 0;
}
Output:

Substring found at position: 10

In this example, strstr is used to search for the substring "brown" within the main string "The quick brown fox jumps over the lazy dog".

If the substring is found, it prints its position within the main string; otherwise, it prints that the substring is not found.

Advantages of strstr 

 Efficiency: strstr is highly optimized and performs efficiently even on large strings, making it suitable for real-world applications.

 Simplicity: It simplifies substring searching tasks by handling the complexity internally, reducing the need for manual string manipulation.

 Standard Library: Being part of the standard C library, strstr is readily available and portable across different platforms and compilers.

 Robustness: strstr is a well-tested function that provides reliable results for substring searches, which helps write robust and error-free code.



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments