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


Download  Run Code

Output:

Delight

 
Here’s another version that uses the strncpy() function provided by the C library:

C


Download  Run Code

Output:

Delight

 
The time complexity of the above solution is O(n).

That’s all about substring function implementation in C.