Search code examples
csubstringc-strings

Alternatives for str.substr using <cstring> library?


Hi I was wondering if there is an alternative of str.substring() in string.h. If not, what is an efficient alternative?


Solution

  • Assuming that we all agree that using c++ it is safer and more professional to use the standard library tools.

    That said, if we're talking about C and not C++, this should be one of the ways to extract a substring with the "string.h" library:

    #include <stdio.h>
    #include <string.h>
    
    int main() {
        char test[] = "abcdef";
        char subtext[3];
        
        memcpy(subtext, &test[1], 2); //Result: "bc"
        subtext[2] = '\0';
        
        printf("%s", subtext);
        
        return 0;
    }