cpp string find all occurence
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, hello, hello, how low?";
std::string toFind = "hello";
size_t pos = str.find(toFind);
while (pos != std::string::npos) {
std::cout << "Substring found at position: " << pos << std::endl;
pos = str.find(toFind, pos + toFind.size());
}
return 0;
}
Explanation for each step:
#include <iostream>
and#include <string>
: Include necessary libraries for input/output and string operations in C++.int main() {
: Beginning of the main function, the entry point of the C++ program.std::string str = "Hello, hello, hello, how low?";
: Declares a string variablestr
and initializes it with a string containing multiple occurrences of the word "hello".std::string toFind = "hello";
: Declares a string variabletoFind
which holds the substring to search for within thestr
string.size_t pos = str.find(toFind);
: Uses thefind
function of thestd::string
class to search for the first occurrence of the substringtoFind
within thestr
string. The position of the first occurrence (if found) is stored in thepos
variable.while (pos != std::string::npos) {
: Enters a while loop that continues as long as thepos
variable stores a valid position (i.e., not equal tostd::string::npos
, which signifies that the substring was not found).std::cout << "Substring found at position: " << pos << std::endl;
: Outputs the position (pos
) where the substringtoFind
was found within thestr
string.pos = str.find(toFind, pos + toFind.size());
: Updates thepos
variable by searching for the next occurrence of the substringtoFind
instr
, starting the search from the position after the previously found occurrence (pos + toFind.size()
).return 0;
: Indicates successful completion of themain()
function and the program, returning 0 to the operating system.