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

标签 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");
}

最佳答案

函数如下所示

#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

关于c++ - 使用 string.find() 确定第 i 个 "str"的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31885852/

相关文章:

c++ - 如何使用 QML 围绕原点缩放 QMesh

string - Tcl:如果变量为空,则默认?

c# - 如何检查适用于字符串的通用对象是否相等

c# - 字符串包含另外两个字符串

c++ - 为什么一个 HANDLE 不适用于 WriteConsoleInput,但适用于 WriteFile?

c++ - 如何在 vector 元素中找到结构数据?

c++ - 无法为二维指针数组分配内存 C++

python - 如何在python中添加像 '1 hour and 5 second '这样的字符串的当前日期

与正则表达式匹配的java字符串

c++ - 可移植 __attribute__ ((__packed__))