How to extract all the substrings between single quotation marks in C

1 Answer

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

#define MAXTOTALSUBS 16

char** extract_substrings(const char* text, int* totalsubs) {
    const char* start = text;
    const char* end;
    char** substrings = malloc(MAXTOTALSUBS * sizeof(char *)); // Allocate memory for 16 substrings
    *totalsubs = 0;

    while ((start = strchr(start, '\'')) != NULL) {
        start++; // Move past the opening quote
        end = strchr(start, '\'');
        if (end == NULL) break; // No closing quote found

        size_t length = end - start;
        // Allocate memory for the substring
        substrings[*totalsubs] = malloc((length + 1) * sizeof(char)); 
        strncpy(substrings[*totalsubs], start, length);
        substrings[*totalsubs][length] = '\0'; // Null-terminate the string
        (*totalsubs)++;
        start = end + 1; // Move past the closing quote
    }

    if (*totalsubs == 0) {
        free(substrings);
        return NULL; // Return NULL if no substrings found
    }

    return substrings;
}

int main() {
    const char* s = "C is a 'widely used' and 'influential' 'general-purpose' programming language";
    int totalsubs;
    char** result = extract_substrings(s, &totalsubs);

    if (result != NULL) {
        for (int i = 0; i < totalsubs; i++) {
            printf("%s\n", result[i]);
            free(result[i]); // Free each substring
        }
        free(result); // Free the array of substrings
    } else {
        printf("\n");
    }

    return 0;
}

  
  
/*
run:

widely used
influential
general-purpose
  
*/
 

 



answered Feb 12, 2025 by avibootz
edited Feb 12, 2025 by avibootz
...