fork(2) download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int main() {
  5. string searchWord;
  6. string userParagraph = "Today is a day like another day";
  7.  
  8. //search for particular word - member function
  9. //std::cout << "Please indicate a word which you like to be found in the paragraph you entered: ";
  10. getline(std::cin, searchWord);
  11.  
  12. //pos determines the position in the array it's in if the word is found and goes until the end of string.
  13. size_t pos = 0;
  14. int wordCount = 0;
  15.  
  16. //npos = not found OR -1.
  17. while (( pos = userParagraph.find(searchWord, pos)) != std::string::npos) {
  18. bool wstart = pos==0 || !isalpha(userParagraph[pos-1]);
  19. bool wend = pos+searchWord.size()==userParagraph.size()
  20. || !isalpha(userParagraph[pos+searchWord.size()]);
  21. if (wstart && wend)
  22. ++wordCount;
  23.  
  24. ++pos;
  25. }
  26.  
  27. if (wordCount == 0) {
  28. std::cout << "The word you entered, '" << searchWord << "', was not found." << std::endl << std::endl;
  29. }
  30. else {
  31. std::cout << searchWord << " was Found " << wordCount << " times." << std::endl << std::endl;
  32. }
  33. }
Success #stdin #stdout 0s 4280KB
stdin
day
stdout
day was Found 2 times.