How to extract a substring between two tags [start] [end] in a string with C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>

/*
 * Extracts the substring between two tags.
 * Parameters:
 *   src   - input string
 *   start - start tag (e.g., "[start]")
 *   end   - end tag   (e.g., "[end]")
 *   out   - buffer to store the extracted substring
 *   outsz - size of the output buffer
 *
 * Returns:
 *   1 on success, 0 if tags not found or invalid.
 */
int extract_between(const char *src, const char *start, const char *end,
                    char *out, size_t outsz) {
    const char *p1 = strstr(src, start);
    if (!p1) return 0;

    p1 += strlen(start);  // move pointer to end of start tag

    const char *p2 = strstr(p1, end);
    if (!p2) return 0;

    size_t len = p2 - p1;
    if (len >= outsz)    // avoid overflow
        return 0;

    memcpy(out, p1, len);
    out[len] = '\0';

    return 1;
}

int main(void)
{
    const char *text = "What do you [start]think about this[end] idea?";
    char result[128];

    if (extract_between(text, "[start]", "[end]", result, sizeof(result))) {
        printf("Extracted: %s\n", result);
    } else {
        printf("Tags not found or output buffer too small.\n");
    }

    return 0;
}



/*
run:

Extracted: think about this

*/

 



answered 18 hours ago by avibootz
edited 18 hours ago by avibootz
...