Code to trim the input string with given index and position

This post is about a program which accepts a string, index and postion and perfors triming. We can say it as a substring program. The index will determine the starting point and the position will determine the end point. This program replicats the substring() which is predefined in java. The bellow code is the c version of the substring function of the String class in java !

Screenshots[Demo]:


The Code:
#include<stdio.h>
char *fs,*ss;
void substring(int a,int b)
{
	int i,j=0;
	ss=(char *)malloc((b-a+1)*sizeof(char));
	for(i=a;i<b;i++,j++)
	{
		ss[j]=fs[i];
	}
	ss[j]='\0';
}
int main()
{
	int a,b;
	fs=(char *)malloc(100*sizeof(char));
	printf("Enter THe String: ");
	gets(fs);
	printf("Enter the value of limit A: ");
	scanf("%d",&a);
	printf("Enter the value of limit B: ");
	scanf("%d",&b);
	substring(a,b);
	printf("The Value of fs is %s and the value of substring is %s",fs,ss);
	return 0;
}


When the string is fetched from the user, along with the index and position values, they are all passed to the substring(). Inside the substring() another variable ss is dynamically allocated according to the space required and so the trimmed string is stored in it. This code snippet can be used in your parent program.

Got bugs, report them !

Comments

Popular posts from this blog

Non Restoring Division Algorithm Implementation in C

Hackerrank Modified Kaprekar Numbers Solution

Bit Stuffing Code Implementation in Java