find substring in string c++
To find a substring in a string in C++, you can use the find()
function from the standard string library. Here is a step-by-step explanation:
Include the necessary header file: Begin by including the
<string>
header file, which contains the definition of thestd::string
class and the required functions.Declare and initialize the string: Declare a string variable and initialize it with the input string you want to search in.
Declare and initialize the substring: Declare another string variable and initialize it with the substring you want to find.
Use the
find()
function: Call thefind()
function on the input string, passing the substring as an argument. Thefind()
function returns the position of the first occurrence of the substring in the string, orstd::string::npos
if the substring is not found.Check the result: Check the result of the
find()
function. If the result isstd::string::npos
, it means the substring was not found. Otherwise, it will give you the position of the substring in the string.
Here is an example of code that demonstrates the above steps:
#include <string>
int main() {
std::string inputString = "Hello, World!";
std::string substring = "World";
size_t found = inputString.find(substring);
if (found != std::string::npos) {
// Substring found
// found contains the position of the first occurrence of the substring
} else {
// Substring not found
}
return 0;
}
In this example, we are searching for the substring "World" in the input string "Hello, World!". The find()
function is called on the inputString
with the substring
as an argument. If the substring is found, the position of the first occurrence is stored in the found
variable. If the substring is not found, std::string::npos
is returned.
You can then perform further operations based on whether the substring is found or not.