Write a program that defines the main string with a value of "Hello C++ World." and checks if a substring "C++" is found in the main string.
You can use the following code structure.
#include <iostream> int main() { //your code here }
#include <iostream> #include <string> int main() { std::string s = "Hello C++ World."; std::string mysubstring = "C++"; auto mysubstringfound = s.find(mysubstring); if (mysubstringfound != std::string::npos) { std::cout << "Substring found at position: " << mysubstringfound << '\n'; } else { std::cout << "Substring was not found." << '\n'; } }
Both the 'C' character and the "C++" substring start at the same position in our main string.
That is why both examples yield a value of 6.
Instead of typing the lengthy std::string::size_type type for our characterfound
and mysubstringfound
variables, we used the auto specifier to deduce the type for us automatically.