Create Sub String From Given String


This operation is used to create a substring from given string. We can also say that it is used to extract a portion of given string.
In order to create a substring we have to specify the starting position(SP) in given string from which we want to create a substring and number of characters(N) to be copy from starting position.
In order to create a substring we have to start from starting position in given string and copy characters into substring until specified number of characters are not copied into substring. Aftrer copying each character from given string into substring the value of N is decremented to keep track of how many characters being copied. The process of copying characters from given string into substring is repeated untill value of N becomes 0.

Algorithm to Create Sub String From Given String


Step 1: Length = 0
SP = SP - 1
Step 2: Repeat step 3 while N > 0
Step 3: S2 [Length] = S1 [SP]
Length = Length +1
SP  = SP +1
N = N-1
Step 4: S2 [Length] = NULL
     

Program to Create Sub String From Given String


#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char *s1,*s2;
int sp,n;
void substr(char *s1,char *s2,int sp,int n);
clrscr();
puts("Enter string:");
gets(s1);
puts("Enter Starting Position:");
scanf("%d",&sp);
puts("Enter Number of characters:");
scanf("%d",&n);
substr(s1,s2,sp,n);
puts("Substring is");
puts(s2);
getch();
}
void substr(char *s1,char *s2,int sp,int n)
{
sp=sp-1;
int length=0;
while(n>0)
{
s2[length]=s1[sp];
sp=sp+1;
length=length+1;
n=n-1;
}
s2[length]='\0';
}

Download Projects


Download Programs