The strstr() function in C searches for a substring in the specified string and returns the position of the first character in the substring or NULL. The function uses the KMP algorithm to preprocess substrings first to improve search efficiency.
Strstr() function usage in C
Definition and syntax
strstr() function is used to find the first occurrence of another substring in a string. The syntax is as follows:
<code class="cpp">char *strstr(const char *str, const char *substr);</code>
Where:
str
: The string to be searched. substr
: The substring to be found. Return value
If the substring is found, the strstr() function returns a string pointer containing the first character of the substring, otherwise it returns NULL
.
Usage Instructions
The strstr() function uses the KMP algorithm (Knuth-Morris-Pratt algorithm) for string matching. It preprocesses substrings first and then scans the string, thus improving search efficiency.
Example Usage
The following code example demonstrates how to use the strstr() function:
<code class="cpp">#include <iostream> #include <cstring> using namespace std; int main() { char str[] = "Hello, world!"; char substr[] = "world"; char *result = strstr(str, substr); if (result) { cout << "Substring '" << substr << "' found at position " << (result - str) << endl; } else { cout << "Substring not found" << endl; } return 0; }</code>
Output:
<code>Substring 'world' found at position 7</code>
Note
NULL
. The above is the detailed content of Usage of strstr function in c++. For more information, please follow other related articles on the PHP Chinese website!