Extract substring from a string
C program to extract a portion of string (Substring Extraction).
Input is taken in two ways:
In first one, user is asked to enter both starting and ending position of the string from where substring is to be extracted. (Method 1)
In second one, only starting position is asked and length of the substring is asked from the user, and corresponding substring is extracted. (Method 2)
In first one, user is asked to enter both starting and ending position of the string from where substring is to be extracted. (Method 1)
In second one, only starting position is asked and length of the substring is asked from the user, and corresponding substring is extracted. (Method 2)
Program
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
#define MAX 50
void main()
{
char str[MAX], sub_str[MAX];
int start, end, len;
int i, j;
printf("Enter the string\t:");
gets(str);
printf("Enter the starting index\t:");
scanf("%d",&start);
printf("Enter the Ending index\t:");
scanf("%d",&end);
len = strlen(str);
if(start < 0 || start > len)
{
printf("\nInvalid start index");
getch();
exit(0);
}
if(end > len)
{
printf("\nInvalid end index");
getch();
exit(0);
}
if(end < start)
{
printf("\nEnding index can not be less than starting index");
getch();
exit(0);
}
j = 0;
for(i=start-1;i<=end-1;i++)
{
sub_str[j] = str[i];
j++;
}
sub_str[j] = '\0';
printf("\nExtracted substring\t:%s",sub_str);
getch();
}
Output
Enter the string :welcome to coursecrux.com
Enter the starting index :3
Enter the Ending index :15
Extracted substring :lcome to cour
Program
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
#define MAX 50
void main()
{
char str[MAX], sub_str[MAX];
int start, length, len;
int i, j;
printf("Enter the string\t:");
gets(str);
printf("Enter the starting index\t:");
scanf("%d",&start);
printf("Enter the length of the substring\t:");
scanf("%d",&length);
len = strlen(str);
if(start < 0 || start > len)
{
printf("\nInvalid start index");
getch();
exit(0);
}
if(start+length > len)
{
printf("\nInvalid length of the substring");
getch();
exit(0);
}
j = 0;
for(i=start-1;i<=start+length-2;i++)
{
sub_str[j] = str[i];
j++;
}
sub_str[j] = '\0';
printf("\nExtracted substring\t:%s",sub_str);
getch();
}
Output
Enter the string :welcome to coursecrux.com
Enter the starting index :5
Enter the length of the substring :10
Extracted substring :ome to cou