C String Test
Syntax
#include <string.h>
char* strstr(const char* str1, const char* str2);
Example
#include <stdio.h>
#include <string.h>
int main () {
const char str1[] = "The quick brown fox jumps over the lazy dog";
const char str2[] = "brown";
char* result = strstr(str1, str2);
if (result) {
printf("The substring is: %s\n", result);
}
else {
printf("Substring not found\n");
}
return 0;
}
Output
The output of the above example will be:
The substring is: brown fox jumps over the lazy dog
Explanation
The strstr()
function is used to search for a substring in a given string. It takes two arguments: str1
is the string to be searched, and str2
is the substring to search for. If the substring is found, a pointer to the first occurrence of the substring in the string is returned. If the substring is not found, a null pointer is returned.
Use
The strstr()
function is commonly used to search for a specific word or token in a string. It can be used in a variety of applications, such as parsing command-line arguments, searching for keywords in a document, or filtering data.
Important Points
- The
strstr()
function returns a pointer to the first occurrence of the substring if it is found. - The
strstr()
function is case-sensitive. - If the substring is not found, a null pointer is returned.
Summary
The C strstr()
function is a useful tool for searching for substrings in strings. It returns a pointer to the first occurrence of a substring in a given string. Its versatility and ease of use make it a popular choice for a variety of applications, from text processing to data filtering. Understanding the basic syntax and behavior of this function is an important part of developing C programming skills.