Is there a C function to find the second occurrence of sub-string in string?
i.e. String - "213 File status 550 Access Denied. 550 Access Denied."
This function would return "550 found twice"....
Is there a C function to find the second occurrence of sub-string in string?
i.e. String - "213 File status 550 Access Denied. 550 Access Denied."
This function would return "550 found twice"....
Have a look at this 'strtok' function found here and on the GNU website here. Here's another link about the strtok function found here also.
Hope this helps, Best regards, Tom.
strstr() returns a pointer to found string, so you can use this to do a second search (bump it by one if first one found).
You could do it like this:
char *yourText = "213 File status 550 Access Denied. 550 Access Denied.";
char *found = strstr(yourText, "550 Access Denied");
if(found != NULL && strstr(found+1, "550 Access Denied"))
{
// second occurrence found
}
But if your intention is to find duplicates in general (i.e. without knowing the search string), you should use a regular expression library which supports matching the same group pattern twice.
If you know the substring you in which you are interested, you could repeatedly call strstr
to find it. If you don't know the substring beforehand (which I suspect is the case), then you might be wanting to find the maximal length repeating string. For that, suffix arrays might be a solution.
Use strstr
.
int count_550s(char const *str)
{
char const *p = str;
int count;
for (count = 0; ; ++count) {
p = strstr(p, "550");
if (!p)
break;
p++;
}
return count;
}
Edit: forgot "return".
You can do that by calling strstr in a loop (haystack refers to the string you are searching in "213 File status 550 Access Denied. 550 Access Denied." while needle refers to the string you are searching for "550"):
unsigned int count = 0;
const char *next = haystack
while ((next = strstr(next, needle)) != NULL)
{
++count;
++next;
}
If two instances of you needle can overly one another (so you are looking for "555", and the string has "5555" in it, this will count two instances). If you don't want that, you should change ++next
to next += strlen(needle);
No, but you can build one yourself.
const char *find_second_substring(const char *findme,const char *str)
{
const char *tmp;
if((tmp = strstr(str,findme)) != null) {
tmp = strstr(tmp +strlen(findme),findme);
}
return tmp;
}