确定第i个" str"的位置使用string.find()

时间:2015-08-07 20:08:57

标签: c++ string

我正在尝试解决一个问题,我需要找到第i个"字符串"的位置。在主字符串中。

离。 :    bearacbear,我需要找到第二个"熊"的位置。 (不使用substr)

这是我当前的解决方案(包含substr的错误,这就是为什么我问是否有更好的方法)

    #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 // for 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;
    for (int i = 0; i < 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");
}

1 个答案:

答案 0 :(得分:0)

该功能可以按以下方式查看

#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 i      = 0;
    std::string::size_type pos    = 0;

    while ( i < n && ( pos = s1.find( s2, pos + length ) ) != std::string::npos )
    {        
        ++i;
        length = s2.size();
    }

    return i == 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;
}    

程序输出

bear
相关问题