Advertisement
avr39ripe

strstrMExample

Dec 24th, 2020
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.89 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. const char* strstrM(const char* str, const char* search)
  4. {
  5.     for (; *str; ++str)
  6.     {
  7.         for (int searchIdx{ 0 }; *(str + searchIdx) == *(search + searchIdx); ++searchIdx)
  8.         {
  9.             if (!*(search + searchIdx + 1)) { return str; }
  10.         }
  11.     }
  12.     return nullptr;
  13. }
  14.  
  15. int main()
  16. {
  17.     char str[]{ "Hello, this beautiful this world! this is that but that is not thi$" };
  18.     char search[]{ "this" };
  19.  
  20.     int foundCnt{ 0 };
  21.  
  22.     for (auto pos{ strstrM(str, search) }; pos; pos = strstrM(pos+1, search),++foundCnt)
  23.     {
  24.         std::cout << "\"" << search << "\" found at " << (pos - str) << '\n';
  25.     }
  26.  
  27.     if ( foundCnt)
  28.     {
  29.         std::cout << "\"" << search << "\" found " << foundCnt << " times!\n";
  30.     }
  31.     else
  32.     {
  33.         std::cout << "\"" << search << "\" not found in \"" << str << "\"\n";
  34.     }
  35.    
  36.     return 0;
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement