Index of nth Occurrence of the string
For this you can use std::string::find
and keep track of the returned position. While doing this you can check to see if the desired string is not found as well and return a -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;
}
You can use the following function
#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;
}
Returns -1 if it can not find the nth occurrence.
There is a find_nth
template function in Boost: 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;
}