特定の文字列が 1 行で n 番目に出現するインデックスを見つけるにはどうすればよいですか? そのインデックスから部分文字列を取得するには、これが必要です。それは c++ の任意の関数を介して可能ですか?
			
			38794 次
		
7 に答える
            16        
        
		
Boost にはfind_nthテンプレート機能があります: 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 << std::distance(a.begin(), r.begin()) << endl;
    return 0;
}
于 2013-09-24T03:08:20.627   に答える
    
    
            11        
        
		
この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;
}
于 2016-05-19T15:18:24.967   に答える
    
    
            8        
        
		
次の機能を使用できます
#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++;
    }
    return res - haystack;
}
n 番目のオカレンスが見つからない場合は -1 を返します。
于 2013-09-24T03:25:35.247   に答える