Implement the substr() function in C.

Write an efficient function to implement substr() function in C. substr() function returns the substring of a given string between two given indices. The prototype of substr() function 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. Here is a C program that implements the substr() function in C. 

int main() {
  char str1[] = "India";
  char str2[25];

  substr(str2, str1, 1, 3);
  printf("\nstr2 : [%s]", str2);
  return (0);
}

substr(char * dest, char * src, int position, int length) {
  dest[0] = '\0';
  strncat(dest, (src + position), length);
}

Here is another C program to do the same

#include <stdio.h> 
#include <conio.h>

void mySubstr(char * dest, char * src, int position, int length);

int main() {
  char subStr[100];
  char str[] = "My Name Is Sweet";

  mySubstr(subStr, str, 1, 5);
  printf("\nstr    = [%s]"
    "\nsubStr = [%s]\n\n", str, subStr);
  getch();
  return (0);
}

void mySubstr(char * dest, char * src, int position, int length) {
  while (length > 0) {
    * dest = * (src + position);
    dest++;

    src++;
    length--;
  }
}

 

C Programming Questions