How to extract substrings in C

1 Answer

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

// A helper that mimics PHP's substr() behavior
char* substr(const char* s, int start, int length) {
    int len = strlen(s);

    // Handle negative start: count from the end
    if (start < 0) {
        start = len + start;
        if (start < 0) start = 0;
    }

    // If length is omitted (length < 0 means cut off from the end)
    if (length < 0) {
        length = len - start + length;
        if (length < 0) length = 0;
    }

    // If length extends beyond string, clamp it
    if (start + length > len) {
        length = len - start;
    }

    // If start is beyond end of string, return empty string
    if (start >= len) {
        char* out = malloc(1);
        out[0] = '\0';
        return out;
    }

    // Allocate and copy substring
    char* out = malloc(length + 1);
    strncpy(out, s + start, length);
    out[length] = '\0';
    
    return out;
}

int main() {
    const char* s = "Start making the future now";

    char* t;

    t = substr(s, 6, 2);  printf("%s\n", t); free(t);
    t = substr(s, 13, -1); printf("%s\n", t); free(t); 
    t = substr(s, -10, -1); printf("%s\n", t); free(t); 
    t = substr(s, -15, 4); printf("%s\n", t); free(t); 
    t = substr(s, 0, -1); printf("%s\n", t); free(t); 
    t = substr(s, 0, -11); printf("%s\n", t); free(t); 
    t = substr(s, 0, 12); printf("%s\n", t); free(t); 
    t = substr(s, 0, 1); printf("%s\n", t); free(t); 
    t = substr(s, -1, 1); printf("%s\n", t); free(t); 

    printf("%c\n", s[0]);                
    printf("%c\n", s[strlen(s) - 1]);    

    return 0;
}



/*
run:

ma
the future no
future no
 the
Start making the future no
Start making the
Start making
S
w
S
w

*/


 



answered Dec 30, 2025 by avibootz
...