C++ string Searching a string for a substring

Description

C++ string Searching a string for a substring

#include <iostream>
#include <string>
using std::string;

int main()/*from  ww  w.  j av  a 2s  . c  om*/
{
  string text{};                                          // The string to  be searched
  string word{};                                          // Substring  to  be found
  std::cout << "Enter the string to be searched and press Enter:\n";
  std::getline(std::cin, text);

  std::cout << "Enter the string to be found and press Enter:\n";
  std::getline(std::cin, word);

  int count{};                                         // Count of substring occurrences
  int index{};                                         // String index
  while ((index = text.find(word, index)) != string::npos)
  {
    ++count;
    index += word.length();
  }
  std::cout << "Your text contained " << count << " occurrences of \""
            << word << "\"." << std::endl;
}



PreviousNext

Related