GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing www.tutorialspoint.com — C++ cstring strstr() Function
Selected Reading
C++ cstring strstr() FunctionThe C++ cstring strstr() Function is used to find the first occurrence of a sub-string in the current string. This is similar to the strchr(), but the difference is that strchr() finds the first occurrence of a character in a string whereas, the strstr() function finds the first occurrence of a substring in a string. Now, let's take an example where you have a DSA question and you need to find the first occurrence of the word 'question' in the string. In this case, you can use the strstr() function. SyntaxFollowing is the syntax of the strstr() function − char *strstr(const char *str1, const char *str2); ParametersParameters of the strstr() function are as follows −
Return ValueThe strstr() function returns a pointer to the first occurrence of the substring str2 in the string str1, or a null pointer if the substring is not found. Example 1Following example demonstrates the basic usage of the C++ cstring strstr() function − Here, we will take a string str and then search for the first occurrence of the substring 'point' in the string using the strstr() function. #include <iostream>
#include <cstring>
using namespace std;
int main() {
char str[] = "tutorialspoint";
char substr[] = "point";
char *ret;
ret = strstr(str, substr);
if(ret) {
cout << "Substring found: " << ret << endl;
} else {
cout << "Substring not found" << endl;
}
return 0;
}
OutputFollowing is the output of the above C++ program: Substring found: point Example 2Now, let's take another example where we will search for the substring that is not present in the string. For this, we will take a string str and then search for the first occurrence of the substring 'xyz' in the string using the strstr() function. #include <iostream>
#include <cstring>
using namespace std;
int main() {
char str[] = "tutorialspoint";
char substr[] = "xyz";
char *ret;
ret = strstr(str, substr);
if(ret) {
cout << "Substring found: " << ret << endl;
}else {
cout << "Substring not found" << endl;
}
return 0;
}
OutputFollowing is the output of the above C++ program − Substring not found Advertisements
|
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |