Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,845 questions

51,766 answers

573 users

How to extract a substring between two tags in C

1 Answer

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

// Function to extract content between specified tags
void extractContentBetweenTags(const char* str, const char* tagName, char* result) {
    char startTag[64], endTag[64];
    sprintf(startTag, "<%s>", tagName);   // Construct the opening tag
    sprintf(endTag, "</%s>", tagName);   // Construct the closing tag

    const char* start = strstr(str, startTag);  // Find the opening tag
    if (start) {
        start += strlen(startTag);  // Move pointer to the content after the opening tag
        const char* end = strstr(start, endTag);  // Find the closing tag
        if (end) {
            size_t length = end - start;  // Calculate the length of the content
            strncpy(result, start, length);  // Copy the content to the result buffer
            result[length] = '\0';  // Null-terminate the string
            return;
        }
    }
    // If tags are not found, return an empty string
    strcpy(result, "");
}

int main() {
    const char* str = "abcd <tag>efg hijk lmnop</tag> qrst uvwxyz";
    const char* tagName = "tag";

    // Buffer to hold the extracted content
    char extractedcontent[256];

    // Call the function to extract the substring
    extractContentBetweenTags(str, tagName, extractedcontent);

    if (strlen(extractedcontent) > 0) {
        printf("Extracted content: %s\n", extractedcontent);
    } else {
        printf("No matching tags found.\n");
    }

    return 0;
}


/*
run:

Extracted content: efg hijk lmnop

*/

 



answered Apr 2, 2025 by avibootz
...