| 3 | #include <string> |
| 4 | |
| 5 | int main() |
| 6 | { |
| 7 | std::string text; // The string to be searched |
| 8 | std::string word; // Substring to be found |
| 9 | std::cout << "Enter the string to be searched and press Enter:\n"; |
| 10 | std::getline(std::cin, text); |
| 11 | |
| 12 | std::cout << "Enter the string to be found and press Enter:\n"; |
| 13 | std::getline(std::cin, word); |
| 14 | |
| 15 | size_t count{}; // Count of substring occurrences |
| 16 | size_t index{}; // String index |
| 17 | while ((index = text.find(word, index)) != std::string::npos) |
| 18 | { |
| 19 | ++count; |
| 20 | index += word.length(); // Advance by full word (discards overlapping occurrences) |
| 21 | } |
| 22 | |
| 23 | std::cout << "Your text contained " << count << " occurrences of \"" |
| 24 | << word << "\"." << std::endl; |
| 25 | } |