How do I find the index of nth occurrence of the given string in a line? I need this to take a substring from that index. Is that possible through any functions in c++?
You can find the nth occurrence of a substring in a string by splitting at the substring with max n+1 splits. If the resulting list has a size greater than n+1, it means that the substring occurs more than n times.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With