Implement substring function in C

Write an efficient function to implement substring function in C. substring() function returns the substring of given string containing n characters starting from given index.

 
 

The prototype of substring function is:

char* substring(char *destination, const char *source, int beg, int n)

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.

Below code implements substring() function which extracts n characters from the source string starting from beg index and return it.

C

Download   Run Code

Output:

Delight

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

C

Download   Run Code

Output:

Delight

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

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz