Is there a C function to find the second occurrence of substring in string?

c, search, string

Solution

Use `strstr`. Since `strstr` returns a pointer to the first occurrence of the needle, you can use the result to find the next occurrence.

For example, to count occurrences of the string `"550"`:

#include <string.h>

int count_550s(const char *str)
{
    const char *ptr = str;
    int count = 0;
    while ((ptr = strstr(ptr, "550")) != NULL) {
        // ptr is pointing at "550...", so we skip
        // over the "550".
        ptr += 3;
        count++;
    }
    return count;
}

Problem

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"....

Original source