strstr Function in C

The strstr() function in C is used to parse and locate the occurrence of a substring in a string. It is defined in the string.h header file.

This short tutorial will show you how to use C’s strstr() function to locate a set substring.

Basic Usage

The syntax for the strstr() function is:

char* strstr(char *str, const char *substr);

The function accepts two arguments: str and the substring. The function then searches for the occurrence of the substr in the string pointed by the str.

NOTE: The function does not include the terminating null characters but stops the search at their first occurrence.

Return Value

If it finds the occurrence of the substring, the function returns a pointer to the first character of the substring. If it does not find the searched substring, the function returns a null pointer.

Strstr() Function Example

The following simple example illustrates how the function works.

#include <stdio.h>
#include <string.h>
int main() {
    char str[] = "Hello From LinuxHint Team";
    char substr[] = "LinuxHint";
    char *i;

    i = strstr(str, substr);

    if (i != NULL) {
        printf("Substring located! %s\n", i);
    }
    else {
        printf("Substring not located!");
    }
    return 0;
}

If we run the code above, we should get an output shown:

Substring located!
LinuxHint Team

Conclusion

That is it for the strstr() function in C. Check out other C tutorials to learn more.



from https://ift.tt/3zk9Sdg

Post a Comment

0 Comments