Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Index of nth Occurrence of the string

Tags:

c++

string

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++?

like image 734
Mohan Avatar asked Sep 24 '13 02:09

Mohan


People also ask

How do you find the index of the nth occurrence of a substring in a string?

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.


1 Answers

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.

like image 177
rcs Avatar answered Sep 20 '22 06:09

rcs