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:

  1. #include <iostream> and #include <string>: These lines include necessary libraries for input/output and string manipulation functionalities.
  2. using namespace std;: This line allows using elements from the standard namespace without explicitly qualifying them.
  3. int main() { ... }: The starting point of the program execution.
  4. string str = "Hello, how are you?";: Declares a string variable str and initializes it with the value "Hello, how are you?".
  5. string substr = "how";: Declares a string variable substr and initializes it with the value "how", which is the substring to be searched.
  6. size_t found = str.find(substr);: Uses the find function on the str string to search for the position of the substr within str. The find function returns the index where the substring starts or string::npos (a special constant) if the substring is not found.
  7. if (found != string::npos) { ... } else { ... }: Checks if the substr is found within the str. If found, it prints the index where the substring starts; otherwise, it prints that the substring was not found.
  8. cout << "Substring found at index " << found << endl;: Outputs the message along with the index where the substring substr was found in the string str.
  9. cout << "Substring not found" << endl;: Outputs a message indicating that the substring substr was not found in the string str.
  10. return 0;: Indicates successful program execution and exits the main function.