Searching a string for a substring - C++ STL

C++ examples for STL:string

Description

Searching a string for a substring

Demo Code

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

int main()//from   w ww. j a  v a  2  s  .  c  o  m
{
  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;
}

Result


Related Tutorials