How to Extract a Substring From a String in C
In this tutorial, we are going to see how to extract a substring from a string in C. In the following program we implement a defined function named extract(). This function takes four arguments, the source string, substring, start index(from) and end index(to), and will return either 0 (in case of successful execution) or 1 (in case of failed execution).
How to Extract a Substring From a String in C
#include <stdio.h>
#include <string.h>
int extract(int from, int to, char *string, char *subString)
{
int i=0, j=0;
//get the length of the string.
int length = strlen(string);
if( from > length || from < 0 ){
printf("The index 'from' is invalid\n");
return 1;
}
if( to > length ){
printf("The index 'to' is invalid\n");
return 1;
}
for( i = from, j = 0; i <= to; i++, j++){
subString[j] = string[i];
}
return 0;
}
int main()
{
char string[100];
char subString[50];
int from,to;
printf("Enter a string: ");
fgets(string,100,stdin);
printf("Enter the index 'from': ");
scanf("%d",&from);
printf("Enter the index 'to': ");
scanf("%d",&to);
printf("The string is : %s",string);
if( extract(from, to, string, subString) == 0 )
printf("The sub-string is : %s", subString);
else
printf("ERROR!\n");
return 0;
}
Output:
Enter a string: Welcome to StackHowTo Enter the index 'from': 11 Enter the index 'to': 20 The string is : Welcome to StackHowTo The sub-string is : StackHowTo





