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.

40,023 questions

51,974 answers

573 users

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