Implement substring function in C
Write an efficient function to implement substring function in C. The substring function returns the substring of a given string containing n characters starting from the given index.
The prototype of the substring() function is:
char* substring(char *destination, const char *source, int beg, int n)
The substring() function returns the substring of the source string starting at the position specified in the third argument and the length specified in the fourth argument of the function.
The following code implements the substring() function, which extracts n characters from the source string starting from the beg index and returns it.
C
|
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 |
#include <stdio.h> // Function to implement substring function in C char* substring(char *destination, const char *source, int beg, int n) { // extracts `n` characters from the source string starting from `beg` index // and copy them into the destination string while (n > 0) { *destination = *(source + beg); destination++; source++; n--; } // null terminate destination string *destination = '\0'; // return the destination string return destination; } // Implement `substring()` function in C int main() { char source[] = "Techie Delight – Ace the Technical Interviews"; char destination[25]; int start = 7; int len = 7; substring(destination, source, start, len); printf("%s\n", destination); return 0; } |
Output:
Delight
Here’s another version that uses the strncpy() function provided by the C library:
C
|
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 |
#include <stdio.h> #include <string.h> // Function to implement substring function in C char* substring(char *destination, const char *source, int beg, int n) { // copy `n` characters from the source string starting from // `beg` index into the destination strncpy(destination, (source + beg), n); // return the destination string return destination; } // Implement `substring()` function in C int main() { char source[] = "Techie Delight – Ace the Technical Interviews"; char destination[25]; int start = 7; int len = 7; substring(destination, source, start, len); printf("%s\n", destination); return 0; } |
Output:
Delight
The time complexity of the above solution is O(n).
That’s all about substring function 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 :)