php strpos
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello, how are you?";
string substr = "how";
size_t found = str.find(substr);
if (found != string::npos) {
cout << "Substring found at index " << found << endl;
} else {
cout << "Substring not found" << endl;
}
return 0;
}
This C++ code demonstrates the usage of the find
function from the <string>
library to search for a substring within a given string. Here's a step-by-step explanation:
#include <iostream>
and#include <string>
: These lines include necessary libraries for input/output and string manipulation functionalities.using namespace std;
: This line allows using elements from the standard namespace without explicitly qualifying them.int main() { ... }
: The starting point of the program execution.string str = "Hello, how are you?";
: Declares a string variablestr
and initializes it with the value "Hello, how are you?".string substr = "how";
: Declares a string variablesubstr
and initializes it with the value "how", which is the substring to be searched.size_t found = str.find(substr);
: Uses thefind
function on thestr
string to search for the position of thesubstr
withinstr
. Thefind
function returns the index where the substring starts orstring::npos
(a special constant) if the substring is not found.if (found != string::npos) { ... } else { ... }
: Checks if thesubstr
is found within thestr
. If found, it prints the index where the substring starts; otherwise, it prints that the substring was not found.cout << "Substring found at index " << found << endl;
: Outputs the message along with the index where the substringsubstr
was found in the stringstr
.cout << "Substring not found" << endl;
: Outputs a message indicating that the substringsubstr
was not found in the stringstr
.return 0;
: Indicates successful program execution and exits themain
function.