Implement substr() function in C
Write an efficient function to implement substr() function in C. The substr() function returns the substring of a given string between two given indices.
The substr function prototype is: char* substr(const char *source, int m, int n)
It returns the substring of the source string starting at the position m and ending at position n-1.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
#include <stdio.h> #include <stdlib.h> // Following function extracts characters present in `src` // between `m` and `n` (excluding `n`) char* substr(const char *src, int m, int n) { // get the length of the destination string int len = n - m; // allocate (len + 1) chars for destination (+1 for extra null character) char *dest = (char*)malloc(sizeof(char) * (len + 1)); // extracts characters between m'th and n'th index from source string // and copy them into the destination string for (int i = m; i < n && (*(src + i) != '\0'); i++) { *dest = *(src + i); dest++; } // null-terminate the destination string *dest = '\0'; // return the destination string return dest - len; } // Implement `substr()` function in C int main() { char src[] = "substr function Implementation"; int m = 7; int n = 12; char* dest = substr(src, m, n); printf("%s\n", dest); return 0; } |
Output:
funct
Following’s another implementation that uses C library’s strncpy() function:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
#include <stdio.h> #include <string.h> #include <stdlib.h> // Following function extracts characters present in `src` // between `m` and `n` (excluding `n`) char* substr(const char *src, int m, int n) { // get the length of the destination string int len = n - m; // allocate (len + 1) chars for destination (+1 for extra null character) char *dest = (char*)malloc(sizeof(char) * (len + 1)); // start with m'th char and copy `len` chars into the destination strncpy(dest, (src + m), len); // return the destination string return dest; } // Implement `substr()` function in C int main() { char src[] = "substr function Implementation"; int m = 7; int n = 12; char* dest = substr(src, m, n); printf("%s\n", dest); return 0; } |
Output:
funct
The time complexity of above functions is O(n – m).
That’s all about substr() implementation in C.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)