c++ - Determine position of ith "str" using string.find() -


i trying solve problem need find position of ith "string" in main string.

ex. : bearacbear ,i need find position of of second "bear" (without using substr)

that current solution ( contain errors substr,that's why asked if there better way)

    #include <iostream> #include <algorithm> #include <iterator> #include <assert.h> #include <cmath> #include <sstream> #include <iomanip> #include <vector> #include <stack> #include <queue> #include <map> #include <set> #include <string> #include <ctime>  #define ull unsigned long long // n^12 #define ll long long #define ld long double #define pb push_back #define mp make_pair #define all(v) v.begin(),v.end() #define rall(v) v.rbegin(),v.rend()  using namespace std;  int main() {     std::ios::sync_with_stdio(false);     cin.tie(0), cout.tie(0);     string str;     cin >> str;     ll ans = 0, len;     (int = 0; < str.size() - 2; i++)     {         string s = str.substr(i, str.size());         len = s.size();         int pos = s.find("bear") + str.size() - s.size();         if (s.find("bear") != string::npos)             ans += (len - pos - 3);     }     cout << ans;     system("pause"); } 

the function can following way

#include <iostream> #include <string>  std::string::size_type find_nth( const std::string &s1, const std::string &s2,                                   std::string::size_type n = 1 ) {     std::string::size_type length = 0;     std::string::size_type      = 0;     std::string::size_type pos    = 0;      while ( < n && ( pos = s1.find( s2, pos + length ) ) != std::string::npos )     {                 ++i;         length = s2.size();     }      return == n && n ? pos : std::string::npos; }  int main() {     std::string s( "bearacbear" );     std::string::size_type n = find_nth( s, "bear", 2 );      if ( n != std::string::npos ) std::cout << s.c_str() + n << std::endl; }     

the program output is

bear 

Comments

Popular posts from this blog

yii2 - Yii 2 Running a Cron in the basic template -

asp.net - 'System.Web.HttpContext' does not contain a definition for 'GetOwinContext' Mystery -

mercurial graft feature, can it copy? -