第n个索引的出现

Moh*_*han 8 c++ string

如何在一行中找到给定字符串第n次出现的索引?我需要这个从该索引中获取子字符串.这可以通过c ++中的任何函数来实现吗?

Vla*_*nko 12

find_nthBoost中有一个模板函数:http://www.boost.org/doc/libs/1_54_0/doc/html/boost/algorithm/find_nth.html

#include <iostream>
#include <boost/algorithm/string/find.hpp>

using namespace std;
using namespace boost;

int main() {

    string a = "The rain in Spain falls mainly on the plain";

    iterator_range<string::iterator> r = find_nth(a, "ain", 2);
    cout << distance(a.begin(), r.begin()) << endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

  • @ huahsin68:索引是基于零的,因为它在find_nth文档中有说明.只需使用1即可找到第二次出现. (2认同)

rcs*_*rcs 6

您可以使用以下功能

#include <string.h>

int strpos(char *haystack, char *needle, int nth)
{
    char *res = haystack;
    for(int i = 1; i <= nth; i++)
    {
        res = strstr(res, needle);
        if (!res)
            return -1;
        else if(i != nth)
            res = res++;
    }
    return res - haystack;
}
Run Code Online (Sandbox Code Playgroud)

如果找不到第n个匹配项,则返回-1.

  • line"res = res ++;" 似乎什么都不做,会把它变成"res ++;" (3认同)

jv7*_*v74 6

为此,您可以使用std::string::find并跟踪返回的位置。在执行此操作时,您可以检查是否也找不到所需的字符串,并返回-1。

#include <string>

int nthOccurrence(const std::string& str, const std::string& findMe, int nth)
{
    size_t  pos = 0;
    int     cnt = 0;

    while( cnt != nth )
    {
        pos+=1;
        pos = str.find(findMe, pos);
        if ( pos == std::string::npos )
            return -1;
        cnt++;
    }
    return pos;
}
Run Code Online (Sandbox Code Playgroud)